Reputation: 225
I have a problem with a search form that searches for multiple words.
I have this function in my model. First, I search the KeyWords
table for the foreign IDs that I need to search the library table.
This works OK when I search for one word on my KeyWords
table but I don't know how to search for multiple words given that each of those words will return a group of ids. I don't know how to collapse them together to search in the library.
This is my search function in my library model:
def self.search(search)
if search
where("id in (?)", KeyWords.where("word like ?", "%#{search}%").pluck(:library_id))
else
all
end
end
What I tried to do was something like spliting the search param, and, for each word in there, search the key_words
:
# array = Array.new
# key_words = search.to_s.split(" ")
# key_words.count.times do |i|
# ids[i] = PalabrasClave.where("palabra like ?", "%#{key_words[i]}%").pluck(:daw_mate_acad_id)
# end
# where("id in (?)", ids.flatten.uniq)
but that does NOT work. I thought the search gave me an array of IDs that I could later collapse together with a join
method, but sadly that does not work. Any ideas?
Upvotes: 2
Views: 532
Reputation: 225
I was calling an array = Array.new
when I should've been initializing ids = Array.new
:
ids = Array.new
key_words = search.to_s.split(" ")
key_words.count.times do |i|
ids[i] = PalabrasClave.where("palabra like ?", "%#{key_words[i]}%").pluck(:daw_mate_acad_id)
end
where("id in (?)", ids.flatten.uniq)
Upvotes: 2