ActiveRecord的,的has_many:通过,多态关联与STI

问题描述:

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://*.com/questions/6582588/rails-structuring-a-query-involving-a-polymorphic-association-and-sti – JamesDS

+0

您是否尝试过最简单的方法 - 将: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