ActiveRecord,has_many:through和Polymorphic Associations

Cor*_*ory 115 activerecord ruby-on-rails polymorphic-associations

伙计们,

想确保我理解正确.请忽略继承的情况(SentientBeing),尝试着重于has_many中的多态模型:通过关系.也就是说,考虑以下......

class Widget < ActiveRecord::Base
  has_many :widget_groupings

  has_many :people, :through => :widget_groupings, :source => :person, :conditions => "widget_groupings.grouper_type = 'Person'"
  has_many :aliens, :through => :widget_groupings, :source => :alien, :conditions => "video_groupings.grouper_type = 'Alien'"
end

class Person < ActiveRecord::Base
  has_many :widget_groupings, :as => grouper
  has_many :widgets, :through => :widget_groupings
end

class Alien < ActiveRecord::Base
  has_many :widget_groupings, :as => grouper
  has_many :widgets, :through => :widget_groupings  
end

class WidgetGrouping < ActiveRecord::Base
  belongs_to :widget
  belongs_to :grouper, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)

在一个完美的世界里,我想,给一个Widget和一个人,做一些像:

widget.people << my_person
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我注意到'grouper'的'type'在widget_groupings中始终为null.但是,如果我喜欢以下内容:

widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person}) 
Run Code Online (Sandbox Code Playgroud)

然后所有的工作正如我通常预期的那样.我不认为我曾经见过这种非多态关联,只是想知道这是否是特定于这个用例的东西,或者我是否有可能盯着一个bug.

谢谢你的帮助!

EmF*_*mFi 160

Rails 3.1.1 存在一个已知问题,它破坏了这一功能.如果您遇到此问题首先尝试升级,则已在3.1.2中修复

你真是太近了 问题是你误用了:source选项.:source应该指向多态的belongs_to关系.然后,您需要做的就是为您尝试定义的关系指定:source_type.

对Widget模型的此修复应该允许您完成您正在寻找的内容.

class Widget < ActiveRecord::Base
  has_many :widget_groupings

  has_many :people, :through => :widget_groupings, :source => :grouper, :source_type => 'Person'
  has_many :aliens, :through => :widget_groupings, :source => :grouper, :source_type => 'Alien'
end
Run Code Online (Sandbox Code Playgroud)

  • 与@Shtirlic提到的相同.有没有办法不指定source_type,所以你有一个混合的结果集?如果有人解决了这个问题,我很想知道如何解决. (5认同)
  • 仍然适用于Rails 4.2.0.但是,如果没有source_type和两个单独的关联,有没有办法实现这一点? (2认同)