2

I have a nested resource in users:

resources :users do
  resources :reservations
end

In my controller actions i can get the current controller name by using controller.controller_name. So in the user show action the controller.controller_name returns "users". Likewise in the reservations show action it returns "reservations".

But when i'm a the nested resource route like "http://mywesite/users/:id/mutations" i would like to get the parent controller of the nested resource, in this case "users". Is there any way in retrieving this using a controller property or route checker? I'm not a fan of regex my url.

I could check my params[:user_id], but could this be error prone? I might have an registrations controller in which the :user_id could be set.

The reason I want to have this parent resource is because i want to create a search form in my layout only when the current action has something to do with users, e.g. all actions that are performed in the users controller or nested resources controller of the users.

Harm de Wit
  • 2,150
  • 2
  • 18
  • 24

1 Answers1

3

In your example http://mywesite/users/:id/mutations will be http://mywesite/users/:user_id/mutations

You may check params[:user_id].present?

See Getting the parent resource from the URL

Community
  • 1
  • 1
gayavat
  • 18,910
  • 11
  • 45
  • 55
  • I voted it up because it works most of the time. However, sometimes you want to know what the master resource is regardless of whether or not you're hitting the nested resource. For that, this doesn't help. – Amin Ariana Mar 22 '13 at 19:44