Rails way to visualize various actions and views based on user type?

I have several different types of users (buyers, sellers, administrators).

I want them all to have the same account_path url, but 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 

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) # 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 

It calls the correct * _show method in the controller. But still trying to display "show.html.erb" and not looking for the correct template that I have there, "admin_show.html.erb", "buyer_show.html.erb", etc.

I know that I can simply manually call render "admin_show" in every action, but I thought there might be a cleaner way to do this all in the previous filter.

Or has anyone else seen a plugin or a more elegant way to break down actions and views by user type? Thanks!

Btw, I use Rails 3 (in case that matters).

+4
source share
1 answer

Depending on how different the presentation templates are, it may be useful to move part of this logic to the show template and switch 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 display. This should work if you configured the @action_name controller. You can do this in your render_by_user method instead of the 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) # 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 
+4
source

All Articles