Atache Atache - 5 months ago 10
Ruby Question

Rails query by multiple keywords

I am trying to create a custom search method for a project I'm working on. Ideally I'd like to be able to have the user input and unlimited number of keywords to filter the results by, but I'm willing to settle for a just a couple. I have my code working for just one keyword. Here is the code in my model:

class Food < ActiveRecord::Base
has_many :meal_items, inverse_of: :food_for_meal, foreign_key: 'food_for_meal_id'
has_many :user_meals, through: :meal_items

def self.search (key)
Food.where("description LIKE ?", "%#{key}%")
end
end


Here is one attempt I have made to use multiple keywords:

class Food < ActiveRecord::Base
has_many :meal_items, inverse_of: :food_for_meal, foreign_key: 'food_for_meal_id'
has_many :user_meals, through: :meal_items

def self.search (key)
keys = key.split('+')
Food.where("description LIKE ?", "%#{keys[0]}%")
AND ("description LIKE ?", "%#{keys[1]}%")
end
end


I have tried moving things in and out of parens and quotes and so forth, but can't seem to nail down the correct syntax. Any help would be appreciated.

Answer

.where takes SQL fragments, so just put the AND inside.

Food.where("description LIKE ? OR description LIKE ?", "%#{keys[0]}%", "%#{keys[1]}%")

You could do something like for n, keys:

Food.where((['description LIKE ?'] * keys.size).join(' OR '), *keys.map{ |key| "%#{key}%" })

EDIT: You probably want OR as pointed out by a commenter in my answer.

Comments