如何在搜索表单中搜索多个记录?

时间:2013-02-21 11:31:53

标签: ruby-on-rails ruby-on-rails-3 search

我试图让用户能够在搜索表单的字段中选择多个记录。

这样的事情:

<%= f.input_field :neighborhood_id, collection: Neighborhood.order(:name), :url => autocomplete_neighborhood_name_searches_path, :as => :autocomplete, 'data-delimiter' => ',', :multiple => true, :class => "span8" %>

它会将其发送到我的search模型,如下所示:@search = Search.create!(params[:search])

这就是Search.rb模型对它的作用:

key = "%#{keywords}%"
listings = Listing.order(:headline)
listings = listings.includes(:neighborhood).where("listings.headline like ? or neighborhoods.name like ?", key, key) if keywords.present?
listings = listings.where(neighborhood_id: neighborhood_id) if neighborhood_id.present?
listings

问题是这只是接受1 neighborhood_id,所以当我选择多个对象时会收到此错误:

undefined method `to_i' for ["Alley Park, Madison"]:Array

Alley ParkMadison是2个社区的名称,而不是ID。

那么我该怎么做呢?

感谢。

修改1

问题似乎不在于查找params[:search]本身,而在于将表单输入转换为条目数组。我尝试将搜索方法更改为:

listings = listings.includes(:neighborhood).where("neighborhoods.name like ?", neighborhood_id) if neighborhood_id.present?   

不要因为我正在查找neighborhood.name并传入neighborhood_id这一事实而感到困惑。我这样做是因为我知道字段neighborhood_id的参数实际上是neighborhood的名称。如果这有效,我会重构一些东西,但事实并非如此。所以不要挂断电话。

但仍然会返回错误undefined method 'to_i'....

此外,即使我只传入1个选项,我仍然会收到错误。

2 个答案:

答案 0 :(得分:1)

listings = listings.where("neighborhood_id in (?) ", neighborhood_id) 

答案 1 :(得分:0)

您可以从输入字段中获取id而不是邻居名称,如下所示:

<%= f.input_field :neighborhood_id, collection: Neighborhood.order(:name), :url => autocomplete_neighborhood_name_searches_path, :as => :autocomplete, 'data-delimiter' => ',', :multiple => true, :class => "span8", :input_html => { :id => "neighborhood_id" } %>