Fellow Stranger
Fellow Stranger

Reputation: 34103

Short way to check for controller/action in view

if params[:controller] == "posts" && params[:action] == "show"

Any shorter Railsy way to check for a certain controller/action-pair than the above?

Something like this?

if couple("posts#show")

Or even like this if multiple actions:

if couple("posts#show/index/edit")

Upvotes: 0

Views: 671

Answers (2)

SDp
SDp

Reputation: 329

There is a rails method for this, it's called current_page?(options)

Basically you can pass as argument what you like (controller, action, controller + action, url, etc)

For more information: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F

Upvotes: 0

markets
markets

Reputation: 7043

You can always define a custom method in your ApplicationController. For simple cases, could be something like:

def couple?(route_path)
  controller, action = route_path.split('#')
  controller_name == controller && action_name == action
end
helper_method :couple?

This way, you are able to use that method in your controllers and views. If you don't really need to use it in your controllers, define it directly into ApplicationHelper.

Upvotes: 2

Related Questions