Search code examples
ruby-on-rails-3routesnested-resources

Issue with named routes for nested resources


I have a rails 3 nested resource defined as follows

resources :candidates do
  collection do
    get :bookmarked
  end
  resources :bookmarks, :only => [:create, :destroy]
end

The bookmarked action in the candidats collection will create a new bookmark for the candidate. This works fine as expected.

The problem arises when I try to delete a bookmark.

I have a link in my candidate show page as follows

<%= link_to "Remove bookmark", candidate_bookmarks_path(@candidate, @bookmark), :method => :delete %>

When I click on this link I get the following error

No route matches "/candidates/1/bookmarks.8"

I was expecting the url to be /candidates/1/bookmarks/8 not what is printed in the error. I was also expecting the request to be directed to the bookmarks controllers destroy method. But clearly that is not happening.

Can someone tell me what I am doing wrong. Any help appreciated.


Solution

  • The path for destroy action should be candidate_bookmark_path(@candidate, @bookmark) instead of candidate_bookmarks_path(@candidate, @bookmark).

    Just remember, you are deleting a specific bookmark of a specific candidate, so the resources should be singular in your path, and you need to pass specific object for each resource.