Search code examples
ruby-on-railsrubyformsroutesnested-resources

Rails nested routing prefix verb issue


My app works as intended, however I have a question in regards to nested routes. In my routes file I have

resources :lists do
    resources :items
end

and when I run rake:routes I get(shortened to save space)

list_items     GET    /lists/:list_id/items(.:format)          items#index
               POST   /lists/:list_id/items(.:format)          items#create
new_list_item  GET    /lists/:list_id/items/new(.:format)      items#new
edit_list_item GET    /lists/:list_id/items/:id/edit(.:format) items#edit
list_item      GET    /lists/:list_id/items/:id(.:format)      items#show

When I follow tutorials or other material, their 'Prefix Verb' would only have action_item (i.e new_item) and the forms would only have

form_for @item

instead of what I have

form_for [@list, @item]

I was wondering if I was missing something, or doing something wrong. Any help or information is appreciated.


Solution

  • It sounds like the tutorial isn't using nested routes. Within your routes you are defining the resources of items within the resources of list (resources are defined based on the RESTful routes)

    So when

    form_for [@list, @item]
    

    is used it knows that to generate the form it recognizes that it is a nested route and the routes with a route that extends to something like '/lists/:list_id/items/:item_id' it needs two ids to know which route to POST to.

    If the tutorial had

    form_for [@item]
    

    it isn't a nested route so the routes are most likely

    resources :items and would generate routes without the lists (i.e. new_item => '/item/item_id') Thats why your routes have the lists included in the prefix verb.

    I am on my phone right now. I will fix the typos and structure in a bit when I get to my computer.