代码之家  ›  专栏  ›  技术社区  ›  Brian Armstrong

Rails如何根据用户类型呈现不同的操作和视图?

  •  4
  • Brian Armstrong  · 技术社区  · 15 年前

    我有两种不同的用户类型(买家、卖家、管理员)。

    我在尝试这样的事情。。。

    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\u by\u 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
    

    它在控制器中调用正确的*\u show方法。但仍试图呈现“显示.html.erb并没有找到正确的模板,我在那里命名为“管理”_显示.html.erb“”买家“”_显示.html.erb“等等。

    我知道我可以手动打电话 render "admin_show" 但我认为在before过滤器中可能有一种更干净的方法来完成这一切。

    或者有没有其他人看到过按用户类型划分操作和视图的插件或更优雅的方法?谢谢!

    顺便说一句,我使用的是rails3(以防有所不同)。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Andrew Vit    15 年前

    show 改为模板并在那里进行切换:

    <% if current_user.is_a? Admin %>
    <h1> Show Admin Stuff! </h1>
    <% 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) # 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