marcamillion
marcamillion

Reputation: 33755

How do I search for multiple records in a search form?

I am trying to allow the user to be able to choose multiple records in a field on the search form.

Something like this:

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

It sends it to my search model like this: @search = Search.create!(params[:search])

This is what the Search.rb model does with it:

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

The issue is that this is just accepting 1 neighborhood_id, so I am getting this error when I choose multiple objects:

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

Where Alley Park and Madison are the names of 2 neighborhoods, not the IDs.

So how do I get this working?

Thanks.

Edit 1

The issue seems to not be in the lookup of the params[:search] per se, but rather in the conversion of the form input to an array of entries. I tried changing the search method to be something like:

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

Don't get hung up on the fact that I am looking up neighborhood.name and passing in neighborhood_id. I just did that because I know that the params for the field neighborhood_id were actually the names of the neighborhood. If this had worked, I would have refactored some stuff, but it didn't. So don't get hung up on that.

But that still returns the error undefined method 'to_i'....

Also, I still get that error even if I just pass in 1 option.

Upvotes: 0

Views: 158

Answers (2)

sjain
sjain

Reputation: 23344

You can get the id instead of neighborhood names from the input field like this:

<%= 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" } %>

Upvotes: 0

Salil
Salil

Reputation: 47472

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

Upvotes: 1

Related Questions