繁体   English   中英

ActiveRecord,has_many:through,与 STI 的多态关联

[英]ActiveRecord, has_many :through, Polymorphic Associations with STI

ActiveRecord、has_many:through 和 Polymorphic Associations中,OP 的示例请求忽略可能的AlienPerson ( SentientBeing )超类。 这就是我的问题所在。

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值现在都由 Rails 存储为SentientBeing (Rails 为这个grouper_type值寻找基础 class)

在这种情况下,修改Widget中的has_many以按类型过滤的正确方法是什么? 我希望能够执行Widget.find(n).peopleWidget.find(n).aliens ,但目前这两种方法.people.aliens都返回空集[]因为grouper_type始终是SentientBeing

您是否尝试过最简单的方法 - 将:conditions添加到has_many:through中?

换句话说,像这样(在 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关联已经在做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM