Reputation: 960
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.
Upvotes: 1
Views: 1057
Reputation: 960
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]}%"
Upvotes: 0
Reputation: 492
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!
Upvotes: 1
Reputation: 3847
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)
Upvotes: 1