views:

439

answers:

4

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

+4  A: 

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
Daniel Vandersluis
Awesome thanks!!!!
Elliot
+1  A: 

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

Staelen
That only works for the entire layout of the page though, doesn't it? Rather than an if in a partial as per the question.
Shadwell
i've edited the code to ApplicationController. In that case, since the actions are used throughout different controllers, it makes better sense now =)
Staelen
It still just sets the layout for the page though, doesn't it?
Shadwell
i would suppose the partials will be used in the page?
Staelen
A: 

You can use layouts for partials too:

<%= render :partial => 'some_partial', :layout => 'wrap_with_stuff' %>

If you want to work out what layout to use dynamically I'd put that in a helper. So you'd end up with

# In your view

<%= render :partial => 'some_partial', :layout => layout_for_my_partial %>

# In your helper

def layout_for_my_partial
    params[:action] == 'show' ? 'show_wrapper' : 'everything_else_wrapper'
end

This will only work in some circumstances, but might be what you're trying to do.

See more here.

http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts

jonnii
A: 

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