Search code examples
ruby-on-railsroutesrails-routingnested-resources

Rails Sub-resources Routing error


I'm having trouble using sub-resources in my Rails application. My goal is to have routes (example application) such as

/people/1/jokes/new /people/1/jokes

The form_for line in my jokes form is turning up the routing error

undefined method `jokes_path'

See all source files here: https://gist.github.com/maclover7/14c9d6eaa0c6731a3ecf


Solution

  • Note that after you put the jokes resource under people as a sub-resource, the route helpers for the jokes change to have user prefix as follows:

      user_jokes_path # => /people/1/jokes
      new_user_jokes_path # => /people/1/jokes/new
      edit_user_jokes_path # => /poople/1/jokes/:id/edit
    

    Also note that you need to pass user.id to the path as part of the parameters, so if you are using user_jokes_path you need to call it by passing the user object, so if your are storing the user record in @user variable:

    <%= link_to 'jokes', user_jokes_path(@user)%>
    

    The best approach is to use rake routes command to see the routes table for your application and find out what it generated