Suppose I have the following models (among others)
class Child
belongs_to :parent1, class_name: "Parent"
belongs_to :parent2, class_name: "Parent"
class Parent
has_many :childs
I want to chain sql active record relations using .merge()
(or .or()
) to minimize # sql queries, and also to keep query concerns reusable & separate, for scalability of a complex data model. I know how to do this for a single parent.
Child.where(**child_criteria).joins(:parent1).merge(ParentActiveRecordRelation)
This will do a
... INNER JOIN "parents" ON "parents"."id" = "childs"."parent1_id" WHERE ... ["parents" attribute criteria] ...
But now I am faced with building an active record relation where ParentActiveRecordRelation could apply to either :parent1 or :parent2. Worse yet, what if I had a Parent1ActiveRecordRelation that applied to :parent1 and a Parent2ActiveRecordRelation that applied to parent2?
I tried chaining two separate merges with an or,
Child.where(**child_criteria).joins(:parent1).merge(Parent1ActiveRecordRelation).or(Child.where(**child_criteria).joins(:parent2).merge(Parent2ActiveRecordRelation))
but rails returns
ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]