简体   繁体   中英

Rails Search Ransack NoMethodError

This app has 2 models, a Farm has_many Crops. We are trying to use ransack to do the searching on Farm#show. The show action in the controller looks like this:

  def show
    @farm = Farm.find(params[:id])
    @q = @farm.crops.ransack(params[:q])
    @crops = @q.result(distinct: true)
  end

The Farm#show View contains this form:

<%= search_form_for @q do |f| %>
  <div>
    <%= f.label :croptype_cont, "Crop Name Contains:" %>
    <%= f.text_field :croptype_cont %>
  </div>
<%= f.submit "search" %>
<% end %>

Everything looks right to me, but we keep getting this error - it highlights the first line of the search form:

NoMethodError in Farms#show
undefined method `crops_path'

What is missing here?

Because by default ranksack search goes to index action, you can see in its documentation which is crops_path , Here You'll have to write a separate action for searching. or you can do like this

1- modify your show action and define only @q as search variable

  def show
    @farm = Farm.find(params[:id])
    @q = @farm.crops.ransack(params[:q])
  end

2- create a separate action for search ex-

def search_crops
  @farm = Farm.find(params[:id])
  @q = @farm.crops.ransack(params[:q])
  @crops = @q.result(distinct: true) 
end 

3- define url for search_crops

get 'search/farm/crops', to: 'farms#search_crops', as: :crops_search

4- in farms/show.html.erb send a hidden field id to get farm before searching crops associated with farm

<%= search_form_for @q, url: crops_search_path, :html => { :method => :get } do |f| 
  <%= f.hidden_field :id, value: params[:id] %>
  <div>
    <%= f.label :croptype_cont, "Crop Name Contains:" %>
    <%= f.text_field :croptype_cont %>
  </div>
<%= f.submit "search" %>
<% end %>

5- so after getting @crops from search_crops action You can either make common partial for show.html.erb as well as search_crops.html.erb and display search results.You can modify your code accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM