Search code examples
ruby-on-railsrubyroutesnested-routes

Understanding how nested routes work in Rails


I am a bit confused. This is my routes file:

enter image description here

When I try this, the link will not be as expected (cl is my checklist):

<%= page_checklist_path(cl) %>

The renders string of the link as:

/pages/31/checklists/4

But it should be

/pages/4/checklists/31

What is the problem here?


Solution

  • When using nested routes like that then you have to provide both instances as arguments. See creating paths and URLs from objects in the Rails guides. That means you need to call your route helper like this:

    <%= page_checklist_path(page, checklist) %> # or
    <%= page_checklist_path(checklist.page, checklist) %>
    

    If you want to avoid that I suggest using shallow nesting. The ID of the checklist is unique in your database anyway, therefore the page ID is not really needed when nesting routes.

    Fun fact: The 4 in the URL from your example is not the page's ID (because you didn't provide a page at all). But nil has the ID 4 in Ruby.