0
在Rails中,我想覆蓋關聯的行爲。例如,默認情況下,如果Person has_many :hats
,調用some_person.hats
將使用person.id
和hat.person_id
進行簡單加入。我可以重寫關聯方法返回的內容嗎?
我想修改該查詢以包含一些其他條件。例如,也許一個人收藏的帽子應該只是適合他們國家的帽子。
看來,我可以做這樣的事情:
class Person < ActiveRecord::Base
has_many :hats, :through => :country do
# John lives in Canada, so he gets a baseball cap and a hockey helmet
self.country.hats
end
end
我所能控制的關聯返回這個樣子?如果不是,範圍是否是最好的解決方案?
我知道這是一個愚蠢的例子,但解釋我所需要的這個域邏輯對於這裏的每個人來說太無聊了。 :)