Hello I struggle creating a specific query.
I have a searchfield with input parameter "{search}". I want to use this search field to find all tables which have a plate with veggies of a specific flavor or description.
I already got a tricky query which does exactly what it is supposed to do - so this works perfectly fine!
Tables.where(id: Plate.select("plate_id").where(Veggie.select("id").where('description LIKE ? OR flavor LIKE ?', "%#{search}%","%#{search}%")))
Aside from Veggies, suppose there is also a SQL-Table calles Fruits. Now i want to search for all Tables which have Plates which have Veggies OR(!!!) Fruits fitting to the description or flavor of the searchfield input.
I experimented a lot but can not find the right way. Here is one of my experiments which does not work though:
Tables.where(id: Plate.select("plate_id").where((Veggie.select("id").where('description LIKE ? OR flavor LIKE ?', "%#{search}%","%#{search}%")).or(Fruit.select("id").where('color LIKE ? OR flavor LIKE ?', "%#{search}%","%#{search}%")))
The code above does not work! The problem is, I can not figure out how to combine those 2 subqueries. The or
statement does not seem to work. Any help appreciated.
EDIT: As has been pointed out, i now tried doing it with the UNION command. Unfortunately the .union() option with the Gem active_record_union seems to work only for rails 4+.
So i simulated a union with the following code.
def self.search2(search2)
if search2
if search2.length > 0
@Plate1 = Plate.where(veggie_id: Veggie.select("id").where('description LIKE ? OR color LIKE ?', "%#{search2}%","%#{search2}%"))
@Plate2 = Plate.where(fruit_id: Fruit.select("id").where('description LIKE ? OR color LIKE ? OR flavor LIKE ?', "%#{search2}%","%#{search2}%", "%#{search2}%" ))
@Plate12 = @Plate1+@Plate2
@table_ids = Array.new
@Plate12.each do |plate|
@table_ids.push(plate.table_id)
end
where(id: @table_ids)
else
scoped
end
else
scoped
end
end
Actually, i do believe this is very messy! It DOES work as intended, but i am a fraid it is a bit slow and unperformant. If anyone has a better suggestion i am glad about any help.