ruby-on-rails – 基于用户类型呈现不同动作和视图的Rails方式?
发布时间:2020-12-17 02:27:19 所属栏目:百科 来源:网络整理
导读:我有几种不同的用户类型(买家,卖家,管理员). 我希望他们都拥有相同的account_path网址,但要使用不同的操作和视图. 我正在尝试这样的事…… class AccountsController ApplicationController before_filter :render_by_user,:only = [:show] def show # see *
我有几种不同的用户类型(买家,卖家,管理员).
我希望他们都拥有相同的account_path网址,但要使用不同的操作和视图. 我正在尝试这样的事…… 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的方法…… 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”等的正确模板. 我知道我可以在每个动作中手动调用渲染“admin_show”,但我认为可能有更简洁的方法在前面的过滤器中执行此操作. 或者让其他人看到插件或更优雅的方式来打破行动&按用户类型查看?谢谢! 顺便说一句,我正在使用Rails 3(如果它有所作为). 解决方法
根据视图模板的不同,将一些逻辑移入show模板并在那里进行切换可能是有益的:
<% if current_user.is_a? Admin %> <h1> Show Admin Stuff! </h1> <% end %> 但要回答您的问题,您需要指定要呈现的模板.如果您设置控制器的@action_name,这应该有效.您可以在render_by_user方法中执行此操作,而不是使用本地操作变量: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |