如何解决Rails根据用户类型重定向
| 我正在通过构建商店应用程序来学习Rails,并且在重定向方面遇到了一些麻烦。我在应用程序中具有3个角色: 买方 卖方 管理员 根据他们登录时所使用的类型,我想重定向到其他页面/操作,但仍为每个页面显示相同的URL(http://.../my-account)。 我不喜欢在同一视图中渲染局部视图,这看起来似乎很混乱,还有另一种方法可以实现这一点吗? 我能想到的唯一方法是在帐户控制器中执行多个操作(例如,买方,卖方,管理员),但这意味着路径看起来像http://.../my-account/buyer或http:// ... /我的帐户/卖家等 非常感谢, 罗杰 我将我的代码放在下面: 型号/user.rbclass User < ActiveRecord::Base
def buyer?
return type == \'buyer\'
end
def seller?
return type == \'seller\'
end
def administrator?
return type == \'administrator\'
end
...
end
controllers / 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
config / routes.rb
match \'my-account\' => \'accounts#show\'
非常感谢,
罗杰
解决方法
在
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
, 如果我理解您的问题正确,那么解决方法很简单。
您可以只在控制器内调用所需的方法。我在我的项目中这样做:
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 \”。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。