我试图让用户能够在搜索表单的一个字段中选择多个记录。
像这样的东西:
<%= 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
WhereAlley Park
和Madison
是 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 个选项,我仍然会收到该错误。