Rafi Rafi - 7 months ago 9
Ruby Question

Rails - Active Record Search ".where" With Or Statement For Same Criteria

In my Rails app, I'm trying to let the user search for products using a key word or key phrase that matches the products' descriptions AND names.

According to the documentation, I have it written like so:

def productSearch
@results = 0
if !params[:searchInput].nil?
@results = 1
@searchInput = params[:searchInput]
@searchCriteria = "%#{params[:searchInput]}%"
@productList = Product.where("description like ? or name like ?", @searchCriteria, @searchCriteria)
end
end


What frustrates me is this line:

@productList = Product.where("description like ? or name like ?", @searchCriteria, @searchCriteria)


Is there a short-hand for matching both the description and name of the product to the same search criteria?

I'd like to also mention that I'm fairly new to Ruby on Rails and this is for a school project where I have to build an e-commerce website with my group, so help with this would be greatly appreciated.

Answer

Try:

@productList = Product.where("description like :search or name like :search", search: @searchCriteria)

Comments