ActiveRecord,has_many:through,与STI的多态关联
在ActiveRecord,has_many:through和Polymorphic Associations中 ,OP的示例请求忽略Alien
和Person
( 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
在这个修改过的例子中, Alien
和Person
的grouper_type
值现在都由Rails存储为SentientBeing
(Rails为此grouper_type
值寻找基类) 。
在这种情况下,修改Widget
的has_many
以按类型过滤的正确方法是什么? 我希望能够做Widget.find(n).people
和Widget.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
关联已经在做了。