take-five / activerecord-hierarchical_query

Simple DSL for creating recursive queries with ActiveRecord
MIT License
119 stars 24 forks source link

recursive has_many queries #40

Open smenor opened 1 year ago

smenor commented 1 year ago

We have a hierarchical tree of X which this works well for but each leaf on that tree has_many Y relations and we need a way to recursively select all of the Y from all descendants of a particular instance x of X

So / in pseudocode

class X < ActiveRecord
  belongs_to :parent, class_name: "X", optional: true, touch: true
  has_many :children, inverse_of: :parent, class_name: "X", foreign_key: :parent

  has_many :y
end

class Y < ActiveRecord
  belongs_to :x
end

Then we would want

x = X.all.sample

ys = x.all_child_ys # this is all elements of Y which are in z.ys for all z which are of type X and children of x

Is there a way to do this now or some ( reasonable ) way to add it as a new feature ?