'Using multiple LIKE statements in an ActiveRecord Query

I am fairly new to Rails. I have been builidng a search bar that goes through all of my products. I got it to work when I am only searching through either the name of the product or the description. But I would like the search term to be compared to both and the product to be displayed if either the name matches the search term or it matches the description.

This is my code at the moment:

if params[:q]
  search = params[:q]
  @products = Product.where("name LIKE ? OR description LIKE ?", "%#{search}%")
else 
  @products = Product.all 
  end

Right now I am getting an error: "Wrong Number of Bind Variable"

I have been trying to google for a solution but I havn't gotten lucky. I would reallz appreciate if someone could help me! Thanks so much.



Solution 1:[1]

If your variables in query have the same value, you can use named key:

@products = Product.where(
  "name LIKE :search OR description LIKE :search", search: "%#{search}%"
)

If they different:

@products = Product.where(
  "name LIKE :first_search OR description LIKE :second_search",
  first_search: "%#{f_search}%", second_search: "%#{s_search}%"
)

or just use question marks:

@products = Product.where(
  "name LIKE (?) OR description LIKE (?)", "%#{f_search}%", %#{s_search}%"
)

Solution 2:[2]

You need to provide search key twice. One for each ?

search_key = "%#{search}%"
@products = Product.where("name LIKE ? OR description LIKE ?", search_key, search_key)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2