hoarse and buggy
stop screaming at your code

Ruby on Rails: Method names for nested resources on the edge (rev 7176)

In my overzealous attempt to learn Ruby on Rails and RESTful design while using Edge Rails, I have once again been bitten by a change that wasn’t obvious to me until I read the CHANGELOG. Feeling pretty macho, I decided to create some nested resources in my application. The code I added to config/routes.rb went like this:

map.resources :users do |users|
   users.resources :projects
end

Then, when trying to create a new project for a user, I created a link that looked like this:

<%= link_to 'New project', new_project_path( @user ) %>

Of course, because nothing ever works on the first try (oh the pain I must endure), this gave me an error:

undefined method `new_project_path' ...

Once again, I commenced beating my head against the wall and crying out about the various injustices done to me in life: “But I’m doing it just like all of the tutorials say I should!” and “I thought that method would get generated for me!” After much drama, I decided to check the CHANGELOG again. Bingo:

* Added :name_prefix as standard for nested resources [DHH].
  WARNING: May be backwards incompatible with your app

    Before:

      map.resources :emails do |emails|
        emails.resources :comments,    :name_prefix => "email_"
        emails.resources :attachments, :name_prefix => "email_"
      end

    After:

      map.resources :emails do |emails|
        emails.resources :comments
        emails.resources :attachments
      end

    This does mean that if you intended to have comments_url go to /emails/5/comments,
    then you'll have to set :name_prefix to nil explicitly.

All this is to say, once I changed my code to the following, everything worked just fine:

   <%= link_to 'New project', new_user_project_path( @user ) %>

And all was well with the world.

5 Responses to “Ruby on Rails: Method names for nested resources on the edge (rev 7176)”

  1. Thank you for this post! I had one of those “I could’ve sworn this was working yesterday” moments before I soon realized that perhaps installing EdgeRails may have futzed-up my project. Tried tracking down what had changed in EdgeRails, but couldn’t find a good area to see the changes (duh, did’nt think to look at the CHANGELOG file).

    Anyways, you just saved me a few hours of cussing and banging my head against the table.

  2. Wish I would’ve found this an hour ago. Thanks for the tip!

  3. Thanks, this was exactly what I needed.

  4. Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

  5. 2 гоша: ну сорри)

    здесь видел ет gamebulletin.ru


Leave a Reply