6
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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    
\$\endgroup\$
  • \$\begingroup\$ very neat! that's why I love rails. - thanks \$\endgroup\$ – ecoologic Mar 25 '12 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.