Say I have two relations that hold records in the same model, such as:
@companies1 = Company.where(...)
@companies2 = Company.where(...)
Ho
For anyone who is stuck with Rails4 and cant use Rails5 .or syntax:
I had a dynamically number of big queries, which had similar conditions ( and therefore also similar results). My rake server would have problems when all of them at once would get instantiated, converted to arrays and then merged.
I needed a ActiveRecord::Relation (not fired yet) to use with find_each.
Looked something like this:
Class Conditions
def initialize
self.where_arr = []
self.joins_arr = []
end
def my_condition1
where_arr << 'customers.status = "active"'
joins_arr << :customer
end
def my_condition2
where_arr << 'companies.id = 1'
end
end
conditions = []
joins = []
# probably call them in a .each block with .send
conditions1 = Conditions.new
conditions1.my_condition1
conditions1.my_condition2
conditions << "(#{conditions1.where_arr.join(' AND ')})"
joins << conditions1.joins_arr
conditions2 = Conditions.new
conditions2.my_condition1
joins << conditions2.joins_arr
Company.joins(joins).where(conditions.join(' OR '))
=> SELECT companies.* FROM companies
INNER JOIN customers ON companies.customer_id = customers.id
WHERE (customers.status = 'active' AND companies.id = 1) OR
(customers.status = 'active')
Its kind of hacky but it works, until you can hopefully migrate to Rails 5