Rails根据用户类型重定向

时间:2011-05-30 20:00:08

标签: ruby-on-rails ruby-on-rails-3 authentication redirect

我正在通过构建商店应用程序来学习Rails,并且我在重定向方面遇到了一些麻烦。我在应用程序中有3个角色:

  • 买家
  • 卖方
  • 管理员

根据他们登录的类型,我想重定向到不同的页面/操作,但每个页面/操作仍显示相同的URL(http://.../my-account)。

我不喜欢在同一个视图中渲染局部视图,它看起来很混乱,还有其他方法可以实现吗?

我能想到的唯一方法是在帐户控制器中有多个操作(例如买方,卖方,管理员),但这意味着路径看起来像http://.../my-account/buyerhttp://.../my-account/seller等。

非常感谢, 罗杰

我把我的代码放在下面:

模型/ user.rb

class User < ActiveRecord::Base
    def buyer?
        return type == 'buyer'
    end

    def seller?
        return type == 'seller'
    end

    def administrator?
        return type == 'administrator'
    end

    ...

end

控制器/ accounts_controller.rb

class AccountsController < ApplicationController  
   def show
   end
end

控制器/ user_sessions_controller.rb

class UserSessionsController < ApplicationController
    def new
        @user_session = UserSession.new
    end

    def create
        @user_session = UserSession.new(params[:user_session])

        if @user_session.save
            if session[:return_to].nil?
            # I'm not sure how to handle this part if I want the URL to be the same for each.
                redirect_to(account_path)
            else
                redirect_to(session[:return_to])
            end
        else
            @user_session.errors.clear # Give as little feedback as possible to improve security.
            flash[:notice] = 'We didn\'t recognise the email address or password you entered, please try again.'
            render(:action => :new)
        end
    end

    def destroy
        current_user_session.destroy
        current_basket.destroy
        redirect_to(root_url, :notice => 'Sign out successful!')
    end
end

配置/ routes.rb中

match 'my-account' => 'accounts#show'

非常感谢, 罗杰

2 个答案:

答案 0 :(得分:4)

UserSessionsController#create(即:登录方法)中,您可以继续重定向到帐户路径(假设转到AccountsController#show),然后根据角色呈现不同的视图。我是这样的:

class AccountsController < ApplicationController  
  def show
    if current_user.buyer?
      render 'accounts/buyer'
    elsif current_user.seller?
      render 'accounts/seller'
    elsif current_user.administrator?
      render 'accounts/administrator
    end
  end
end

更好的是,你可以通过惯例来做到这一点......

class AccountsController < ApplicationController  
  def show
    render "accounts/#{current_user.type}"
  end
end

答案 1 :(得分:0)

如果我理解你的问题是正确的,那么解决方案很简单。

您可以在控制器中调用所需的方法。我在我的项目中这样做:

def create
  create_or_update
end

def update
  create_or_update
end

def create_or_update
  ...
end

在你的情况下应该是:

def action
  if administrator? then
    admin_action
  elsif buyer? then
    buyer_action
  elseif seller? then
    seller_action
  else
    some_error_action
  end
end

但是,您可能应该在每个操作中使用操作名称显式调用“render”。

相关问题