3

I defined the following custom Rails route in routes.rb:

resources :projects do
    get 'members' 
end

This results in the following route (output from rake routes):

project_members GET        /projects/:project_id/members(.:format)

What I would like, though, is for the route to map to this instead (change :project_id to :id)

project_members GET        /projects/:id/members(.:format)

How can I make that happen?

Andy R.
  • 199
  • 2
  • 13

1 Answers1

4

Is members a nested resource? If so define it as one, and understand that this is why you have :project_id in the route, because :id in a nested resource is used by the final child item - you can't have multiple nested resources all using the same variable to define their id.

resources :projects do 
  resources :members
end

Add in a third level of nesting and it becomes a bit clearer to explain:

resources :projects do 
  resources :members do
    resources :colours
  end
end

With this nesting you could visit app/projects/:project_id/members/:member_id/colours/:id which would be served by the colours controller, which knows that :id defines an instance of that controllers model, and any other named id's belong to other resources.

Otherwise I think you just need to define it as a member method:

resources :projects do
  member do 
    get 'members'
  end
end

This tells the route that the action members is a non-resource action belonging to an instance of project, which I think should sort you out, but be sure it's the right thing to do.

See section 2.10 of Rails Routing from the Outside In

Matt
  • 13,948
  • 6
  • 44
  • 68
  • No, members is not a nested resource in this case. For the sake of the question, just consider 'members' as some action on a project. – Andy R. Nov 22 '13 at 00:24
  • @AndyR. The last code block in my answer should do what you want then. – Matt Nov 22 '13 at 01:10
  • 2
    Sorry, it was confusing since the "member" keyword happens to be the same name as the action. But yes, it works. Thank you! – Andy R. Nov 22 '13 at 06:35