Search code examples
ruby-on-railsrails-routing

Not all member routes get an id in the querystring


Some member routes with specific names are not added with the expected :id inside the query string. These routes:

resources :tests do
  member do
    get :foo
  end
end

resources :contacts do
  member do
    get :foo
  end
end


resource :tasks do
  member do
    get :foo
  end
end

resource :fruits do
  member do
    get :foo
  end
end

resource :cars do
  member do
    get :foo
  end
end

resources :appointments do
  member do
    get :foo
  end
end

Produces this:

           foo_test GET          /tests/:id/foo(.:format)                   tests#foo
        foo_contact GET          /contacts/:id/foo(.:format)                contacts#foo
          foo_tasks GET          /tasks/foo(.:format)                       tasks#foo
         foo_fruits GET          /fruits/foo(.:format)                      fruits#foo
           foo_cars GET          /cars/foo(.:format)                        cars#foo
    foo_appointment GET          /appointments/:id/foo(.:format)            appointments#foo

Tasks, fruits and cars do not have an id. Why is that?


Solution

  • Your problem is in resource (singular) vs resources (plural). You will notice that everytime you have an :id in your route (test, contact, appointments) it is declared using resources and otherwise using resource.

    By using resource (singular) you are implicitly saying that you have only one resource of this type so there is no need for and id, that's why it's not present here.

    You can find more infos here : Difference between resource and resources methods