Rails: routing and path helpers [duplicate]

2019-08-29 13:26发布

问题:

Possible Duplicate:
Rails: Routing without plurals gives strange helpers

Turns out I had :resources qtl_table in config/routes.rb twice! I get this error:

undefined local variable or method `search_qtl_table_index' for #<#<Class:0x805aff3e0>:0x805af47b0>

in app/views/qtl_table/index.html.erb:

<h2>Search for QTL</h2>
<%= form_tag search_qtl_table_index, :method => 'get' do %>
        <%= text_field_tag :search, params[:search] %>
        <%= submit_tag "Search", :name => nil %>
<% end %>

and in config/routes.rb:

Qtl::Application.routes.draw do
    resources :qtl_table do
            collection do
                    get 'search'
            end
    end
  ...
end

yes I do have plurals turned off:

ActiveRecord::Base.pluralize_table_names = false

Output of rake routes:

              search_qtl_table_index GET    /qtl_table/search(.:format)                            {:action=>"search", :controller=>"qtl_table"}
                     qtl_table_index GET    /qtl_table(.:format)                                   {:action=>"index", :controller=>"qtl_table"}
                                     POST   /qtl_table(.:format)                                   {:action=>"create", :controller=>"qtl_table"}
                       new_qtl_table GET    /qtl_table/new(.:format)                               {:action=>"new", :controller=>"qtl_table"}
                      edit_qtl_table GET    /qtl_table/:id/edit(.:format)                          {:action=>"edit", :controller=>"qtl_table"}
                           qtl_table GET    /qtl_table/:id(.:format)                               {:action=>"show", :controller=>"qtl_table"}
                                     PUT    /qtl_table/:id(.:format)                               {:action=>"update", :controller=>"qtl_table"}
                                     DELETE /qtl_table/:id(.:format)                               {:action=>"destroy", :controller=>"qtl_table"}

回答1:

You may have plurals turned off, but this only affects the table names in the database, not how Rails handles routes.

Because the search route belongs to a collection, not a member, it acts on multiple model objects. Therefore, the route should be search_qtl_tables_path, note plural tables.

qtl_table is a model, and you want to search a collection of them, so it make senses that the route reads like "search multiple records".

edit: My main concern is that your rake routes shouldn't be showing those qtl_table routes twice. Are you repeating yourself somewhere in routes.rb?

OK, so you've deleted the extra routes. Now, this should work...

<%= form_tag search_qtl_table_index_path, :method => 'get' do %>


回答2:

Try:

Qtl::Application.routes.draw do
    resources :qtl_table do
        collection do
                get 'search', :as => 'search_qtl_table'
        end
    end
  ...
end