I would like to do a query with activerecord (not rails) with multiple keywords that are contained in a field (so I have to use LIKE) but I don't know in advance how many keywords there will be.
My query looks like this, Word is my model.
query = ['word1','word2'] #could be more puts "searching for #{query}" qwords = Word.none query.each do |qword| puts qwords.where("word like ?", "%#{qword}%").to_sql qwords = qwords.where("word like ?", "%#{qword}%") end Which gives nothing because the queries are added as AND but I need OR.
searching for ["word1", "word2"] SELECT "words".* FROM "words" WHERE (word like '%word1%') SELECT "words".* FROM "words" WHERE (word like '%word1%') AND (word like '%word2%') #<ActiveRecord::Relation []> I can't use Word.where(word: query) which uses the sql IN keyword because that only works for exact matches.
Is there a solution that doesn't involves concatenating the whole SQL that is needed ?
Word.none? I've not seen that before.qwords.where("word like ? , "qtabs.word"). Does passing it a table.column reference work any different than just an array? I'm thinking there might be something there because it's happening at the SQL level and not the ActiveRecord level? Depends on your DB I would guess.