Rails way to render different actions & views based on user type?

前端 未结 1 1355
不知归路
不知归路 2021-02-10 16:29

I have a couple different user types (buyers, sellers, admins).

I\'d like them all to have the same account_path URL, but to use a different action and view.

I\'

相关标签:
1条回答
  • 2021-02-10 17:10

    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 %>
    

    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
    
    0 讨论(0)
提交回复
热议问题