I have some basic search implemented and I am trying to match multiple attribute to the 1 set of keywords.
I have this:
listings = Listing.order(:headline)
listings = listings.where("headline like ?", "%#{keywords}%") if keywords.present?
I have multiple attributes for listings
that I would like to check to see if the keywords
appear in - e.g. say listing.neighborhood.name
or listing.type.name
.
How do I write all of that in 1 statement? I tried:
listings = listings.where("headline like ? or neighborhood.name like ?", "%#{keywords}%")
But that returned this error:
ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 2) in: headline like ? or neighborhood.name like ?
One obvious solution is just to add "%#{keywords}%"
again...but that hardly seems DRY.
How do I add check both the neighborhood.name
and type.name
and others in that 1 query? Or should I be approaching this another way?
Thanks.
Edit 1:
When I try the non-DRY way of simply adding another {keywords}
parameter, this is the error I get:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: neighborhood.name: SELECT "listings".* FROM "listings" WHERE (headline like '%sterling place%') AND (headline like '%sterling place%' or neighborhood.name like '%sterling place%') ORDER BY headline.
Which I think is because neighborhood
is a foreign_key on my listings
model, and not an attribute in and of itself. There is a simple association between the listings
& neighborhood
model.