为了账号安全,请及时绑定邮箱和手机立即绑定

ActiveRecord,has_many:through和多态关联

ActiveRecord,has_many:through和多态关联

慕标5832272 2019-12-09 09:46:17
民间,想要确保我正确理解了这一点。并且请忽略此处的继承情况(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'"endclass Person < ActiveRecord::Base  has_many :widget_groupings, :as => grouper  has_many :widgets, :through => :widget_groupingsendclass Alien < ActiveRecord::Base  has_many :widget_groupings, :as => grouper  has_many :widgets, :through => :widget_groupings  endclass WidgetGrouping < ActiveRecord::Base  belongs_to :widget  belongs_to :grouper, :polymorphic => trueend在一个完美的世界中,我想给一个小部件和一个Person,执行以下操作:widget.people << my_person但是,当我这样做时,我注意到widget_groupings中“分组器”的“类型”始终为空。但是,如果我执行以下操作:widget.widget_groupings << WidgetGrouping.new({:widget => self, :person => my_person}) 然后所有的工作都像我通常期望的那样。我认为我从未见过这种情况发生在非多态关联中,只是想知道这是否是该用例所特有的,或者我是否有可能盯着一个错误。谢谢你的帮助!
查看完整描述

3 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

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


查看完整回答
反对 回复 2019-12-09
?
慕神8447489

TA贡献1780条经验 获得超1个赞

有很多:through和多态不能一起使用。如果您尝试直接访问它们,它将引发错误。如果我没记错的话,您必须手写widget.people和push例程。

我不认为这是一个错误,只是还没有实现。我想我们会在功能中看到它,因为每个人都有可以使用它的情况。


查看完整回答
反对 回复 2019-12-09
  • 3 回答
  • 0 关注
  • 550 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信