0

這個程序有2個模型,農場has_many莊稼。我們正嘗試使用ransack在Farm#show上進行搜索。在控制器的show動作看起來是這樣的:Rails搜索遍歷NoMethodError

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

農場#顯示視圖包含這種形式:

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

一切看起來我的權利,但我們不斷收到這個錯誤 - 它突出的第一搜索表單的行:

NoMethodError在農場#節目
未定義的方法`crops_path」

這裏缺少什麼?

回答

0

因爲在默認情況下rankingack搜索進入索引操作,您可以在其文檔中看到這是crops_path,這裏您必須編寫一個單獨的搜索操作。或者你可以像這樣

1-修改你的表演動作和只定義@q的搜索變量

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

2 - 創建一個搜索單獨行動EX-

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

3-定義在farms/show.html.erb網址search_crops

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

4-發送HID書房場id與搜索相關的農場作物

<%= 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-所以從search_crops行動越來越@crops後,您可以使公共部分爲show.html.erb以及search_crops.html.erb 和顯示搜索results.You可以修改之前得到您的農場代碼相應