![](/img/trans.png)
[英]ActiveRecord, has_many :through, and Polymorphic Associations
[英]ActiveRecord, has_many :through, Polymorphic Associations with STI
在ActiveRecord、has_many:through 和 Polymorphic Associations中,OP 的示例请求忽略可能的Alien
和Person
( SentientBeing
)超类。 这就是我的问题所在。
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
在这个修改后的示例中, Alien
和Person
的grouper_type
值现在都由 Rails 存储为SentientBeing
(Rails 为这个grouper_type
值寻找基础 class) 。
在这种情况下,修改Widget
中的has_many
以按类型过滤的正确方法是什么? 我希望能够执行Widget.find(n).people
和Widget.find(n).aliens
,但目前这两种方法( .people
和.aliens
)都返回空集[]
因为grouper_type
始终是SentientBeing
。
您是否尝试过最简单的方法 - 将:conditions
添加到has_many:through
中?
换句话说,像这样(在 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
关联已经在做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.