Richard Cook
Richard Cook

Reputation: 33099

Obtaining ID of containing resource via params[:id] for custom actions

I have the following routes in my config/routes.rb file:

resources :employees do
  get 'dashboard'
  get 'orientation'
end

employees refers to a regular resource handling the standard RESTful actions. dashboard and orientation are what I currently refer to "custom actions" which act on Employee instances. I apologize if I have my terminology mixed up and dashboard and orientation are really something else. These custom actions respond to URLs as follows:

http://myhost/employees/1/dashboard

i.e. They're "member" actions much like show, edit etc.

Anyway, this all works well enough. Regular actions such as show on EmployeesController obtain the ID of the associated Employee through params[:id]. However, with this current structure, dashboard and orientation have to use params[:employee_id] instead. This is not too difficult to deal with, but does lead to some additional code complexity as my regular before_filters which expect params[:id] don't work for these two actions.

How do I have the routing system populate params[:id] with the ID for these custom actions in the same way as show etc.? I've tried various approaches with member instead of get for these actions but haven't got anything to work the way I would like yet. This app is built using Ruby on Rails 3.2.

Upvotes: 0

Views: 113

Answers (2)

Kuldeep
Kuldeep

Reputation: 884

This might help you:

resources :employees do
  member do
    get 'dashboard'
    get 'orientation'
  end
end

and the above will generate routes like below, and then you will be able to use params[:id] in your EmployeesController.

dashboard_employee   GET    /employees/:id/dashboard(.:format)          employees#dashboard
orientation_employee GET    /employees/:id/orientation(.:format)        employees#orientation

Upvotes: 2

d_ethier
d_ethier

Reputation: 3911

I haven't tested this example, but you can set the resourceful paths explicitly.

Something like this might work:

resources :employees, path: '/employees/:id' do
  get 'dashboard', path: '/dashboard'
  get 'orientation', path: '/orientation'
end

Upvotes: 0

Related Questions