2014-07-02 89 views
2

我正在嘗試查找與我的Person,自加入,記錄及其所有子元素相關的所有朋友。獲取自加入對象及其子元素上的所有關聯對象

這是我試圖運行的一個示例。我有一個人的記錄,讓我們叫它@person,有4個'孩子'。

這些孩子都有很多朋友。

當我查詢@person時,我希望自己的所有朋友,然後是它下面的四個孩子。

有沒有辦法做到這一點沒有去:friends = @parent.friends + @parent.children.map {|c| c.friends }

真的很喜歡用一個數據庫查詢來做到這一點。我的數據庫也是postgresql。

這裏是我的記錄如何設置的例子。

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 
+0

對於孩子,foregin鍵應該是'id'而不是'paren t_person_id' –

+0

@arivarasan - 它的工作原理是如何設置的。我絕對能夠找到孩子和記錄的父母。我記錄中的字段是:'id:integer,parent_genre_id:integer,title:string,created_at:datetime,updated_at:datetime'。 –

回答

3

至於兒童,你foreign_key必須ID

has_many :children, :class_name => "Person", :foreign_key => "id" 

試試這個:

people_ids = @parent.children.map(&:id).push(@parent.id) 
Friend.where(person_id: people_ids) 

或者你可以渴望的負載關聯的表是這樣的:

friends = Person.includes(:friends).where("parent_person_id = ? or id = ?", [@parent.id, @parent.id]).map(&friends) 
+0

感謝您的回答。我知道我可以抓住所有孩子的身份證來做類似於你的回答的事情。我可以用兩個數據庫查詢來做到這一點,而不是使用'.pluck(:id)'將所有記錄拖入ruby。任何想法如何將你的兩個數據庫查詢合併爲一個? –

+0

好吧,嘗試加載,像Person.includes(:friends).where(id:people_ids)這樣的東西,我不認爲你可以消除調用子查詢壽。 –

+0

爲什麼不考慮使用像MongoDB這樣的NoSQL DB,你將能夠將數據嵌入到Person表中,並且需要不斷的時間來查詢結果? –

1

祖先

你爲什麼不看ancestry gem

這基本上允許你在你的模型中定義children而不必定義關聯(從而防止不必要的查詢)。你就可以做到這一點是這樣的:

#app/models/person.rb 
Class Person < ActiveRecord::Base 
    has_ancestry 
end 

寶石會在您的表,你可以用「子」對象來填充一個ancestry柱:

enter image description here

這可以讓你選擇模型的children這樣的:

@person = Person.find params[:id] 
@person.children.each do |child| 
    child.name 
end 

這裏有各種方法has_ancestry追加到y我們model

enter image description here

-

買者

一個警告的情況是,如果你想多嵌套項目,你需要使用父母組整個樹就像我們上面的例子:

parent_id_1/parent_id_2 
+1

是的,我看了看那個傢伙。我目前所需要的是過度殺傷力。截至目前,確實只有父母和孩子的一級。不過肯定會記住它! –

相關問題