Rafi Rafi - 1 year ago 55
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)

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 Source


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download