ActiveRecord,has_many:through和多态关联

民间,


想要确保我正确理解了这一点。并且请忽略此处的继承情况(SentientBeing),而尝试着重于has_many:through关系中的多态模型。也就是说,请考虑以下事项...


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

在一个完美的世界中,我想给一个小部件和一个Person,执行以下操作:


widget.people << my_person

但是,当我这样做时,我注意到widget_groupings中“分组器”的“类型”始终为空。但是,如果我执行以下操作:


widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person}) 

然后所有的工作都像我通常期望的那样。我认为我从未见过这种情况发生在非多态关联中,只是想知道这是否是该用例所特有的,或者我是否有可能盯着一个错误。


谢谢你的帮助!


慕标5832272
浏览 553回答 3
3回答

慕村9548890

Rails 3.1.1的一个已知问题破坏了此功能。如果您首先遇到此问题,请尝试升级,此问题已在3.1.2中修复。你好亲近 问题是您滥用了:source选项。:source应该指向多态的belongs_to关系。然后,您要做的就是为要定义的关系指定:source_type。对Widget模型的此修复应允许您完全按照自己的意愿进行操作。class Widget < ActiveRecord::Base&nbsp; has_many :widget_groupings&nbsp; has_many :people, :through => :widget_groupings, :source => :grouper, :source_type => 'Person'&nbsp; has_many :aliens, :through => :widget_groupings, :source => :grouper, :source_type => 'Alien'end

慕神8447489

有很多:through和多态不能一起使用。如果您尝试直接访问它们,它将引发错误。如果我没记错的话,您必须手写widget.people和push例程。我不认为这是一个错误,只是还没有实现。我想我们会在功能中看到它,因为每个人都有可以使用它的情况。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby