Fabian W.
Fabian W.

Reputation: 61

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.

Upvotes: 2

Views: 6415

Answers (2)

Oleh  Sobchuk
Oleh Sobchuk

Reputation: 3722

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

Upvotes: 15

RAJ
RAJ

Reputation: 9747

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)

Upvotes: 3

Related Questions