Rails 呈现不同动作的方式基于用户类型的视图? [英] Rails way to render different actions & views based on user type?
问题描述
我有几种不同的用户类型(买家、卖家、管理员).
I have a couple different user types (buyers, sellers, admins).
我希望它们都具有相同的 account_path URL,但使用不同的操作和视图.
I'd like them all to have the same account_path URL, but to use a different action and view.
我正在尝试这样的事情...
I'm trying something like this...
class AccountsController < ApplicationController
before_filter :render_by_user, :only => [:show]
def show
# see *_show below
end
def admin_show
...
end
def buyer_show
...
end
def client_show
...
end
end
这就是我在 ApplicationController 中定义 render_by_user 的方式...
This is how I defined render_by_user in ApplicationController...
def render_by_user
action = "#{current_user.class.to_s.downcase}_#{action_name}"
if self.respond_to?(action)
instance_variable_set("@#{current_user.class.to_s.downcase}", current_user) # e.g. set @model to current_user
self.send(action)
else
flash[:error] ||= "You're not authorized to do that."
redirect_to root_path
end
end
它在控制器中调用正确的 *_show 方法.但仍然尝试呈现show.html.erb"并且没有寻找我在其中名为admin_show.html.erb"buyer_show.html.erb"等的正确模板.
It calls the correct *_show method in the controller. But still tries to render "show.html.erb" and doesn't look for the correct template I have in there named "admin_show.html.erb" "buyer_show.html.erb" etc.
我知道我可以在每个操作中手动调用 render "admin_show"
但我认为在 before 过滤器中可能有一种更简洁的方法来完成这一切.
I know I can just manually call render "admin_show"
in each action but I thought there might be a cleaner way to do this all in the before filter.
或者有没有其他人看到过插件或更优雅的方式来分解动作&按用户类型查看?谢谢!
Or has anyone else seen a plugin or more elegant way to break up actions & views by user type? Thanks!
顺便说一句,我使用的是 Rails 3(以防万一).
Btw, I'm using Rails 3 (in case it makes a difference).
推荐答案
根据视图模板的不同,将某些逻辑移到 show
模板中并执行以下操作可能会有所帮助那里的切换:
Depending on how different the view templates are, it might be beneficial to move some of this logic into the show
template instead and do the switching there:
<% if current_user.is_a? Admin %>
<h1> Show Admin Stuff! </h1>
<% end %>
但是要回答您的问题,您需要指定要呈现的模板.如果您设置了控制器的 @action_name
,这应该可以工作.您可以在 render_by_user
方法中执行此操作,而不是使用本地 action
变量:
But to answer your question, you need to specify which template to render. This should work if you set up your controller's @action_name
. You could do this in your render_by_user
method instead of using a local action
variable:
def render_by_user
self.action_name = "#{current_user.class.to_s.downcase}_#{self.action_name}"
if self.respond_to?(self.action_name)
instance_variable_set("@#{current_user.class.to_s.downcase}", current_user) # e.g. set @model to current_user
self.send(self.action_name)
else
flash[:error] ||= "You're not authorized to do that."
redirect_to root_path
end
end
这篇关于Rails 呈现不同动作的方式基于用户类型的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!