为has_many关系定制sql

时间:2014-06-21 20:12:19

标签: ruby-on-rails activerecord ruby-on-rails-4 arel

我有两张桌子:

地点,这是自我反复的:

int id,
string name,
int location_id 

和节点:

int id,
string name,
int location_id

关系是:

class Node
  belongs_to :location
end

class Location
  has_many :nodes
end

这是有效的,但我不仅想要一个位置的直接关联节点,还想要那些与该位置的任何子节点相关联的节点。我有一个带有一些CTE的Select语句,它正好存档:

with sublocations (name, id, lvl) as 
(
  select 
    l.name,
    l.id,
    1 as lvl
  from locations l
  where l.id = 10003
  union all
  select 
    sl.name,
    sl.id,
    lvl + 1 as lvl
  from sublocations inner join locations sl
  on (sublocations.id = sl.location_id)
)
select 
  sl.name as location, 
  sl.id as location_code,
  n.name
from sublocations sl join nodes n on n.LOCATION_ID = sl.ID;

但是我怎样才能在has_many关系中引入它?

谢谢,Jan

0 个答案:

没有答案