Gordon White
Gordon White

Reputation: 27

Rails Routes - How to get nested IDs from URI Pattern

In my router I have nested two ressources:

resources :servers do
  member do
    resources :maintenances
  end
end

which results in URI pattern as follows:

         maintenance GET    /servers/:id/maintenances/:id(.:format)      maintenances#show

In maintenance_controller's show action I want to get these IDs like:

@server = Server.find_by(params[:id])
@maintenance = Maintenance.find_by ???

My Question is: How can I access these two IDs in my maintenance_controller from the URI pattern http://localhost/servers/1/maintenances/1

Upvotes: 0

Views: 633

Answers (1)

rogelio
rogelio

Reputation: 1569

Try this

resources :servers do
  resources :maintenances
end

Then you can access the nested resource as follow

server_maintenance GET    /servers/:server_id/maintenances/:id(.:format)

In your controller

@server = Server.find(params[:server_id])
@maintenance = Maintenance.find(params[:id])

The complete documentation about routing in rails is in the official docs

Upvotes: 3

Related Questions