Search code examples
ruby-on-rails-3routesform-fornested-resources

Rails form_for with nested resources: "No route matches"


I have the following nested resources in my routes.rb file. The inner resource specifies a controller name.

resources :batches, :except => [:new], :path => "sets" do
  resources :tags, :controller => "batches_tags"
end

In the view for BatchesTags#new, I am trying to build a form:

<%= form_for [@batch, @tag], :url => batch_tag_path do |f| %>
  ...
<% end %>

Attempting to load this page (/sets/1/tags/new) gives me a ActionController::RoutingError with the message:

No route matches {:action=>"show", :controller=>"batches_tags"}

But when I run $ rake routes, it clearly shows this route does exist:

batch_tag GET    /sets/:batch_id/tags/:id(.:format)        {:action=>"show", :controller=>"batches_tags"}

Does anyone know how to fix this error?

Edit:

In the view for Batches#show, I use that same batch_tag_path function and it works perfectly:

<%= link_to "...", batch_tag_path(@batch, tag) %>

Solution

  • It turns out that, while batch_tag_path is a valid route (making the "No route matches" error message very confusing), the path I needed was the pluralized batch_tags_path, as seen in this $ rake routes output:

    batch_tags GET    /sets/:batch_id/tags(.:format)   {:action=>"index", :controller=>"batches_tags"}
               POST   /sets/:batch_id/tags(.:format)   {:action=>"create", :controller=>"batches_tags"}
    

    Perhaps the error message meant that batch_tag_path wasn't a valid route for POST?