Ruby on rails 包含所有多态记录的多态查询

Ruby on rails 包含所有多态记录的多态查询,ruby-on-rails,ruby-on-rails-3,activerecord,polymorphism,Ruby On Rails,Ruby On Rails 3,Activerecord,Polymorphism,我有以下3种型号: class One < ActiveRecord::Base has_many :locations, as: :locatable, dependent: :destroy has_many :countries, through: :locations, order: :name end class Two < ActiveRecord::Base has_many :locations, as: :locatable, dependent

我有以下3种型号:

class One < ActiveRecord::Base
   has_many :locations, as: :locatable, dependent: :destroy
   has_many :countries, through: :locations, order: :name
end

class Two < ActiveRecord::Base
   has_many :locations, as: :locatable, dependent: :destroy
   has_many :countries, through: :locations, order: :name
end

class Three < ActiveRecord::Base
   has_many :locations, as: :locatable, dependent: :destroy
   has_many :countries, through: :locations, order: :name
end
class-One

如何构建包含所有三个模型的所有记录的ActiveRecordRelation?

模型
一个
两个
三个
除了通过多态关系外,彼此之间没有关联,因此您需要转到其中一个类以获得所需的结果

因此,假设所有记录都有一个
位置
,您的
可定位
类被称为
位置
;您应该能够使用以下方法获取所有记录:

Location.all.each do |location|
  location.locatable # <-- this would be an individual record from either One, Two, or Three
end
Location.all.each do |位置|

location.locatable#您可以将STI和多态关联结合起来:

class Locatable < ActiveRecord::Base
  has_many :locations, as: :locatable, dependent: :destroy
  has_many :countries, through: :locations, order: :name
end

class One < Locatable
end

class Two < Locatable
end

class Three < Locatable
end

通过一些验证,以防止系统创建可定位对象,但只创建继承的模型:(有点像将可定位作为“伪”抽象类)

class Locatable
无法创建包含所有三个模型的所有记录的关系,因为:

  • 您不能直接在不同的模型之间创建关系,除非通过
    join
    ,然后您就有了混合记录
  • 通过多态可定位引用创建的任何关系都将限于被引用的记录,并且实际上不包含这些记录,仅包含对这些记录的引用

您能用伪代码说明您希望查询指定的内容吗?如果您只需要全部,只需执行*.all并将结果添加到结果数组中。@t问题的关键是我需要的是ActiveRecordRelation,而不是数组。您尝试过继承吗?Class Twobash
示例当我在Ruby类和JS类之间徘徊时,我每天都会在Ruby类中添加JS花括号。
@locatables = Locatable.scoped # => returns all types of locatable objects
class Locatable < ActiveRecord::Base
  ALLOWED_TYPES = %w( One Two Three )
  validates :locatable_type, inclusion: { in: self::ALLOWED_TYPES }