Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails conditional ('if') statements based on controller action

There might be a better way to do this, but I'm trying to make an if statement in rails, based on the current action, in a controller (this will be used in a view).

For example, if its the edit page, or the show page, etc. I'd like a different style for something - is there an if statement that can specify this?

(I need an if statement, because its used in a partial, on multiple pages).

Thanks!

Elliot

like image 951
Elliot Avatar asked Aug 25 '09 15:08

Elliot


3 Answers

The params hash that is available in the controller contains :controller and :action keys, which specify the controller and action names of the request.

Therefore you could say

if params[:action] == "foo"
  # Show stuff for action 'foo'
elsif params[:action] == "bar"
  # Show stuff for action 'bar'
elsif ...
  # etc.
end
like image 184
Daniel Vandersluis Avatar answered Oct 18 '22 18:10

Daniel Vandersluis


It's not good practice IMO to have partials asking what the current controller and action names are. Think "tell, don't ask" (http://www.pragprog.com/articles/tell-dont-ask). That is, rather than having the partial ask it's caller about its state, tell the partial what you want it to do.

One way to do this is by passing variables to the partial through the locals option:

<%= render :partial => "/common/toolbar", :locals => {:edit => true} %>

Then in the partial:

<% if defined?(edit) && edit %>
... stuff appropriate to edit mode
<% end %>
like image 28
showaltb Avatar answered Oct 18 '22 18:10

showaltb


You can do it this way:

class ApplicationController < ActionController::Base
  layout :set_layout

  def set_layout
    case params[:action]
    when "foo"
      "foo_layout"
    when "bar"
      "bar_layout"
    ...
    else
      "default_layout"
    end
  end

  ...

end

hope it helps =)

like image 4
Staelen Avatar answered Oct 18 '22 17:10

Staelen