2013-04-14 107 views
0

我想要有一種奇怪的關聯。比方說,我有以下類:紅寶石協會:有一個很多 - 有可能嗎?

class Kid < ActiveRecord::Base 
    belongs_to :parent 
    has_one :friend 
end 

class Friend < ActiveRecord::Base 
    belongs_to :kid 
end 

class Parent < ActiveRecord::Base 
    has_many :kids 
    has_one :friend, :through => :kid #This is the "problematic line" 
end 

我知道過去的關係(has_one :friend)是不可能的,沒有意義。但讓我們說,我知道第一個孩子的朋友總是有足夠的信息爲我的父實例,所以我想要得到它像'parent.friend'而不是parent.kids.first.friend

回答

0

不,這沒有任何意義。如果父母有很多孩子,那麼他們不能只有一個朋友,他們會擁有和孩子一樣多的朋友。

Parent.friend沒有任何意義 - 哪個孩子的朋友?

如果它總是第一個,做一個函數:

def first_friend 
    kids.first.friend 
end 

如果你想要的朋友列表...

def friends 
    kids.map(&:friend) # note this queries immediately, it is not a named scope 
end 

如果你想要去的另一個方向來獲取列表對於父母的朋友,在朋友模型中使用一個已命名的範圍:

named_scope :for_parent, lambda {|p| joins(:kids).where('kids.parent_id = ?', p)} 
+0

我同意這種方法,我只需要處理一個奇怪的代碼我描述的場景似乎是合乎邏輯的:\ ...只是想確保我沒有錯過任何東西。不管怎麼說,還是要謝謝你.... – benams