2011-07-05 46 views
9

ActiveRecord, has_many :through, and Polymorphic Associations中,OP的示例請求忽略的AlienPersonSentientBeing可能的超類。這是我的問題所在。ActiveRecord的,的has_many:通過,多態關聯與STI

class Widget < ActiveRecord::Base 
    has_many :widget_groupings 

    has_many :people, :through => :widget_groupings, :source => :person, :source_type => 'Person' 
    has_many :aliens, :through => :widget_groupings, :source => :alien, :source_type => 'Alien' 
end 

SentientBeing < ActiveRecord::Base 
    has_many :widget_groupings, :as => grouper 
    has_many :widgets, :through => :widget_groupings 
end 


class Person < SentientBeing 
end 

class Alien < SentientBeing 
end 

在本變形例爲AlienPersongrouper_type值現在都存儲由滑軌作爲SentientBeing(滑軌尋求出的基類此grouper_type值)

在這種情況下,修改has_manyWidget以按類型過濾的正確方法是什麼?我希望能夠做Widget.find(n).peopleWidget.find(n).aliens,但目前這些方法.people.aliens)都返回空集[]因爲grouper_type總是SentientBeing

+0

這個問題與我之前發佈的[1]非常相似。 這是一個有趣的問題,因爲像你說的,'grouper_type'屬性只存儲超類。似乎需要的是小部件和sentient_beings表之間的連接。像我用過的一個更冗長的查詢可能會適合你,但它不是很好 - 因此我問我的問題。 [1]:http://stackoverflow.com/questions/6582588/rails-structuring-a-query-involving-a-polymorphic-association-and-sti – JamesDS

+0

<3匿名反對票。 – deefour

回答

13

您是否嘗試過最簡單的方法 - 將:conditions添加到has_many :through s?

換句話說,這樣的事情(在widget.rb):

has_many :people, :through => :widget_groupings, :conditions => { :type => 'Person' }, :source => :grouper, :source_type => 'SentientBeing' 
has_many :aliens, :through => :widget_groupings, :conditions => { :type => 'Alien' }, :source => :grouper, :source_type => 'SentientBeing' 

JamesDS是正確的,一個連接需要 - 但它不是寫在這裏,因爲has_many :through協會已經在做了。

+0

非常感謝,這就是我一直在尋找的。 – deefour