ActiveRecord的,的has_many:通过,多态关联与STI
问题描述:
在ActiveRecord, has_many :through, and Polymorphic Associations中,OP的示例请求忽略的Alien
和Person
(SentientBeing
)可能的超类。这是我的问题所在。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
在本变形例为Alien
和Person
的grouper_type
值现在都存储由滑轨作为SentientBeing
(滑轨寻求出的基类此grouper_type
值)。
在这种情况下,修改has_many
的Widget
以按类型过滤的正确方法是什么?我希望能够做Widget.find(n).people
和Widget.find(n).aliens
,但目前这些方法(.people
和.aliens
)都返回空集[]
因为grouper_type
总是SentientBeing
。
答
您是否尝试过最简单的方法 - 将: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
这个问题与我之前发布的[1]非常相似。 这是一个有趣的问题,因为像你说的,'grouper_type'属性只存储超类。似乎需要的是小部件和sentient_beings表之间的连接。像我用过的一个更冗长的查询可能会适合你,但它不是很好 - 因此我问我的问题。 [1]:http://*.com/questions/6582588/rails-structuring-a-query-involving-a-polymorphic-association-and-sti – JamesDS
deefour