【发布时间】:2010-12-13 14:04:19
【问题描述】:
伙计们,
想确保我理解正确。并且请忽略此处的继承情况(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
在一个完美的世界中,给定一个 Widget 和一个 Person,我想执行以下操作:
widget.people << my_person
但是,当我这样做时,我注意到 widget_groupings 中“grouper”的“type”始终为 null。但是,如果我像以下这样:
widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person})
然后一切都按我通常的预期工作。我认为我从未见过非多态关联会发生这种情况,只是想知道这是否是此用例特有的东西,或者我是否可能正在盯着一个错误。
感谢您的帮助!
【问题讨论】:
标签: ruby-on-rails activerecord polymorphic-associations