Ruby on rails 基于用户类型的Rails重定向
我正在通过构建一个商店应用程序来学习Rails,我在重定向方面遇到了一些问题。我在应用程序中有3个角色:Ruby on rails 基于用户类型的Rails重定向,ruby-on-rails,ruby-on-rails-3,authentication,redirect,Ruby On Rails,Ruby On Rails 3,Authentication,Redirect,我正在通过构建一个商店应用程序来学习Rails,我在重定向方面遇到了一些问题。我在应用程序中有3个角色: 买主 卖方 管理员 根据他们登录的类型,我想重定向到不同的页面/操作,但仍然为每个页面显示相同的URL(http://.../my-account) 我不喜欢在同一个视图中渲染partials,它看起来很混乱,有没有其他方法来实现这一点 我能想到的唯一方法是在accounts controller中有多个操作(例如买方、卖方、管理员),但这意味着路径看起来像或等等 非常感谢,, 罗杰 我
- 买主
- 卖方
- 管理员
罗杰如果我正确理解了你的问题,那么解决办法很简单 您可以在控制器中调用所需的方法。我在我的项目中这样做:
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”。在
usersessioncontroller\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
更好的是,你可以按照惯例来做
class AccountsController < ApplicationController
def show
render "accounts/#{current_user.type}"
end
end
class AccountsController
太好了,非常感谢。我不知道渲染函数,我以为只有重定向到一个。
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
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