2014-10-16 66 views
0

我有Parent誰擁有很多Children,但只有一個FirstbornFirstbornChild與「長子」的相關ChildTypeRails 4:父has_one具有特定相關子類型的子項

class Parent 
    has_many :children 
    has_one :firstborn, -> { includes(:child_type).references(:child_type).where("child_type.name = ?", "firstborn") }, class_name: "Child" 
end 

class Child 
    belongs_to :parent 
    belongs_to :child_type 
end 

class ChildType 
    has_many :children 
end 

下面的代碼確實工作:

parent = Parent.find(1)  # => <parent object> 
firstborn = parent.firstborn # => nil 

的最終目標是能夠檢索所有家長和初生兒的孩子在1個查詢。

parents_and_firstborn = Parent.includes(:firstborn) 

我在尋找一個只執行1個查詢和檢索Parent及相關Firstborn孩子的解決方案。

我已經回顧了有關has_one的Rails 4.0.2 API文檔,但是他們的示例 沒有一個像我想要做的那樣跨越多個表。

更新:2014年10月16日14:40

下面的 「作品」,但我不知道爲什麼:

parent = Parent.includes(:firstborn).find(1) # => <parent with firstborn>

爲什麼我不能檢索firstborn AFTER我已經檢索到Parent,但是如果我在原始查詢中返回它includes(...)嗎?

解決方案:2014年10月16日14:50

我有一個attr_accessor :firstborn還停留在以前的嘗試是解決這一問題的Parent模型。當我刪除未使用的代碼時,has_one :firstborn ...代碼按預期工作。

回答

1

看起來是正確的(ish),你應該調試正在執行的SQL。

我真的質疑ChildType表的優點,從我在這裏看到的。你的模式看起來過於複雜。你爲什麼不使用firstbborn布爾?

+0

我很樂意使用替代模式設計......但是,我正在使用遺留系統,我無法對其進行更改。相信我,我已經嘗試了幾個月,因爲這個問題以及許多其他問題。對於特定的問題,我可能需要查詢/過濾多個ChildTypes。 – 2014-10-16 18:32:28

+0

如果顯示兩種情況下返回的SQL;我們可能會有更好的運氣來幫助您調試。 – 2014-10-16 18:45:20

+0

哦...我發現了問題。我現在覺得很蠢!當我正在處理這個問題時,在我決定使用'has_one'關聯之前,我創建了一個'attr_accessor:firstborn'。該訪問器方法是返回'nil'的。一旦我刪除了,上面的代碼實際上按預期工作。我討厭傳統系統! – 2014-10-16 18:51:58

相關問題