I have two Tables:
Locations, which is self-refential:
int id,
string name,
int location_id
and Nodes:
int id,
string name,
int location_id
The Relations are:
class Node
belongs_to :location
end
class Location
has_many :nodes
end
That works, but i want not only the direct associated Nodes for an Location but also that Nodes, wich are associated to any Child of the Location. I have an Select Statement with some CTE, which archives exactly this:
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;
But how can i bring this in the has_many Relation?
Thanks, Jan