Get all associated objects on self join objects and its children

Tuesday, July 1, 2014

I am trying to find all the associated friends with my Person, self-join, record and all its children.


Here is an example I am trying to run. I have a Person record, lets call it @person, that has 4 'children'.


These children all have many friends.


When I query @person, I want all the friends of itself and then the four children below it.


Is there a way to do this without going: friends = @parent.friends + @parent.children.map {|c| c.friends }?


Would really love to do it with one database query. My database is postgresql also.


Here is an example of how my records are set up.



class Person < ActiveRecord::Base

belongs_to :parent, :class_name => "Person", :foreign_key => "parent_person_id"
has_many :children, :class_name => "Person", :foreign_key => "parent_person_id"
has_many :friends

end

class Friend < ActiveRecord::Base
belongs_to :person
end






http://ift.tt/1xex6vR