2011-08-16 16 views
0

我一直在試圖弄清楚這一點,但是什麼是最好的根據它們的單一依賴屬性找到所有主體。例如,比方說,我有這些模型:根據他們的屬性找到所有一對一主體對象

class Principal < ActiveRecord::Base 
    has_one :dependent 
end 

class Dependent < ActiveRecord::Base 
    belongs_to :principal 

    attr_accessible :color 
end 

我怎樣才能查詢數據庫,給我回所有那些家屬有藍色的校長?如果答案不一樣,如果我想要一個範圍(例如:顏色實際上是:數字,並且我希望所有依賴人數落在10-20範圍內的主體),該怎麼辦。

這裏是最接近的解決方案,我有這個問題,我敢肯定,這terribad:

principal_collection = Array.new 
Dependent.where(:color => 'blue').each do |d| 
    principal_collection << d.principal 
end 

感謝提前:)我道歉,如果答案是在那裏,我試圖尋找。

回答

0

也許你找到了?

Principal.includes(:dependent).where("dependents.color = ?", "blue") 
相關問題