1

I have a table called Toys that has the columns toy_id, company_id, store_id, name and description

I am trying to do a query on the table like the following: toys = @company.toys.where("store_id = ? AND (name LIKE ? OR description LIKE ?)", params[:store_id], params[:query], params[:query]

The idea is if the user goes to the following url: https://myapp.com/api/toys/search?store_id=8&query="robot" that it will return all the toys for the store denoted by store_id that have a name or description LIKE robot. Each time it returns empty JSON. Not exactly sure why? Any help or guidance would be appreciated.

Zack Herbert
  • 942
  • 1
  • 16
  • 39

3 Answers3

1

Using Arel style:

companies = Company.arel_table

toys = @company.where(store_id: params[:store_id]).where(companies[:name].matches(params[:query]).or(companies[:description].matches(params[:query])))

Or even:

companies = Company.arel_table

search_query = companies[:name].matches(params[:query]).or(companies[:description].matches(params[:query]))

toys = @company.where(store_id: params[:store_id]).where(search_query)
lcguida
  • 3,787
  • 2
  • 33
  • 56
1

As You 'have a table called Toys', You could try something like this:

@toys = Toy.where("company_id = ? AND store_id = ? AND (name LIKE ? OR description LIKE ?)", params[:company_id], params[:store_id], params[:query], params[:query]

I hope it will help You!

0

Refer to the first comment in the original question by @PardeepDhingra

toys = @company.toys.where("store_id = ? AND (name LIKE ? OR description LIKE ?)", params[:store_id], "%#{params[:query]}%", "%#{params[:query]}%"
AJ X.
  • 2,729
  • 1
  • 23
  • 33
Zack Herbert
  • 942
  • 1
  • 16
  • 39