Search code examples
rubyruby-on-rails-3urlroutesnested-resources

Correct route for a singular nested resource


I have 2 resources, one being a nested resource of another:

parent_resource and child_resource.

This gives me the following routes:

somesite.com/parent_resources/14
somesite.com/parent_resources/14/child_resources/1

However there is only ever going to be a single child_resource for each parent_resource, so to someone using the site this is very confusing. I would like the child_resource paths to look like this:

somesite.com/parent_resource/14/child_resource
somesite.com/parent_resource/14/child_resource/edit
etc

What is the correct way to do this?

My routes.rb

resources :parent_resources do

   resource :child_resource do
   end

end 

From the rails guide to routing:

A singular resourceful route generates these helpers:

new_geocoder_path returns /geocoder/new
edit_geocoder_path returns /geocoder/edit
geocoder_path returns /geocoder

But what about show?

My routes generated by rake routes:

parent_resource_child_resource      POST   /parent_resources/:parent_resource_id/child_resource(.:format)                 child_resources#create


new_parent_resource_child_resource  GET    /parent_resources/:parent_resource_id/child_resource/new(.:format)             child_resources#new

edit_parent_resource_child_resource GET    /parent_resources/:parent_resource_id/child_resource/edit(.:format)            child_resources#edit

                                    GET    /parent_resources/:parent_resource_id/child_resource(.:format)                 child_resources#show

                                    PUT    /parent_resources/:parent_resource_id/child_resource(.:format)                 child_resources#update

                                    DELETE /parent_resources/:parent_resource_id/child_resource(.:format)                 child_resources#destroy

Solution

  • In your routes, define the child resource using the singular resource method:

    resources :parent_resources do
      resource :child_resource
    end
    

    By convention, the controller for the child will still be ChildResourcesController, plural.

    Rails has a pretty good guide to routing. See the section on singular resources.