Rails基于用户类型呈现不同动作和视图的方式?
我有几种不同的用户类型(买家,卖家,管理员)。
我希望他们都拥有相同的account_pathurl,但要使用不同的操作和视图。
我正在尝试这样的事……
class AccountsController [:show] def show # see *_show below end def admin_show ... end def buyer_show ... end def client_show ... end end
这就是我在ApplicationController中定义render_by_user的方法……
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) # eg 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”等的正确模板。
我知道我可以在每个动作中手动调用render "admin_show"
,但我认为可能有更render "admin_show"
方法在前一个filter中执行此操作。
或者是否有其他人看过插件或更优雅的方式来按用户类型分解操作和视图? 谢谢!
顺便说一句,我正在使用Rails 3(如果它有所作为)。
根据视图模板的不同,将一些逻辑移入show
模板并在那里进行切换可能是有益的:
<% if current_user.is_a? Admin %> Show Admin Stuff!
<% end %>
但要回答您的问题,您需要指定要呈现的模板。 如果您设置控制器的@action_name
这应该有效。 您可以在render_by_user
方法中执行此操作,而不是使用本地action
变量:
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) # eg 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