How to manage different views

I answered a question in stackoverflow but I gave a solution that looks a little dirty to me, I'd like your opinion because I think there is a much smarter way to do it.

A guest user should be able to choose between two different view modalities.

My approach was to implement an action and store the choice in the session. I paste some relevant code here as well:

  # application_controller.rb
def set_view_type # TODO: here is the part I don't like
session[:view_type] = params[:view_type]
redirect_to :back
end

# x_controller.rb
def index
case session[:view_type].to_sym
when :box render 'index_box'
else      render 'index_list'
end
end


Then I use two link_to (instead of radiobutton as in stackoverflow) to choose the view, and those should be visible anytime in the layout, this is why I use application_controller for that.

PS: I don't know if it's correct to ask for a question that it's still open in SO, feel free to answer straight there by me, I just think here I'm posting my solution that I would like to be revised.

For the part you do not like, you can set a before_filter in ApplicationController. Therefore a redirect will not be necessary. Selection form can resubmit to the current page with "view_type" parameter.

#application_controller.rb
before_filter :check_view_type, :only => [:index]

def check_view_type
session[:view_type] = params[:view_type] if params[:view_type].present?
end


For this specific example I would prefer layout and partial views. It is well described in Rails guides.

#x/index.html.erb
render :partial => 'item', :layout => current_layout, :collection => @items

#application_controller.rb
helper_method :current_layout

def supported_layouts
[nil]
end

def current_layout
supported_layouts.include? session[:view_type] ? session[:view_type] : supported_layouts.first
end

#x_controller.rb
def supported_layouts
%w[box list]
end

def index
# only index logic
end

• very neat! that's why I love rails. - thanks – ecoologic Mar 25 '12 at 16:28