ActiveRecord,has_many:through,与STI的多态关联

在ActiveRecord,has_many:through和Polymorphic Associations中 ,OP的示例请求忽略AlienPerson SentientBeing的可能超类。 这是我的问题所在。

 class Widget  :widget_groupings, :source => :person, :source_type => 'Person' has_many :aliens, :through => :widget_groupings, :source => :alien, :source_type => 'Alien' end SentientBeing  grouper has_many :widgets, :through => :widget_groupings end class Person < SentientBeing end class Alien < SentientBeing end 

在这个修改过的例子中, AlienPersongrouper_type值现在都由Rails存储为SentientBeing (Rails为此grouper_type值寻找基类)

在这种情况下,修改Widgethas_many以按类型过滤的正确方法是什么? 我希望能够做Widget.find(n).peopleWidget.find(n).aliens ,但是目前这两种方法.people.aliens )都返回空set []因为grouper_type总是SentientBeing

你有没有尝试过最简单的事情 – 为has_many :through添加: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关联已经在做了。