Featured post
ruby on rails 3 - Use Arel for a nested set & join query and convert to ActiveRecord::Relation -
i have model organisations (nested set). have model people. person can have person deputy. organisation owned person. organisation visible owning person or deputy.
i retrieve organisations visible given person, ie. organisations owned person or owned people, given person deputy:
o = arel::table.new(:organisations) p = arel::table.new(:people) pd = p.where(p[:id].eq(3).or(p[:deputy_id].eq(3))).project(:id) op = o.join(p).where(o[:person_id].in(pd)).project("distinct organisations.*)
there better way formulate last join, split query people , deputies query of organisations visible people , deputies.
the last join returns arel::selectmanager (for there seems no useful documentation anywhere).
is there way convert selectmanager activerecord::relation benefit whole concept of "closure under composition"?
how self join above query on organisations again obtain descendants of organisations visible person or deputy? know sql fail selectmanager self join on organisations.
seems there no takers answer , i've found solution approach myself:
1. convert last join activerecord::relation
organisation.where(o[:id].in(op))
the issue this calls arel::selectmanager.to_a
comes deprecation warning (and expensive operation). haven't found alternative though (suspect there none , deprecation warning 1 of inconsistencies observable in arel , it's adoption in activerecord).
2. self-join on nested set descendants
o = organisation.scoped.table op = organisation.where(o[:person_id].in(person.self_and_deputies(person_id).project(:id))).arel o1 = arel::table.new(:organisations, :as => "o1") o2 = arel::table.new(:organisations, :as => "o2") o3 = o1.join(o2).on( o1[:lft].gteq(o2[:lft]).and( o1[:rgt].lteq(o2[:rgt]))).where( o2[:id].in(op)).project("distinct o1.id") organisation.where(o[:id].in(o3))
- Get link
- X
- Other Apps
Comments
Post a Comment