我有以下三种型号:
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如何构建包含所有三个模型的所有记录的ActiveRecordRelation?
发布于 2013-12-19 16:55:24
您可以组合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然后你可以简单地做:
@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 }发布于 2013-12-19 16:18:59
除了通过多态关系之外,模型One、Two和Three并不相互关联,因此您需要使用其中的一个类来获得所需的结果。
因此,假设所有记录都有一个location,并且您的locatable类被称为Location;您应该能够使用如下所示的方式获取所有记录:
Location.all.each do |location|
location.locatable # <-- this would be an individual record from either One, Two, or Three
endFYI,您可以找到更多关于多态关系的信息,以及如何在basics.html#polymorphic-associations中使用它们。
发布于 2013-12-19 17:05:05
不能创建包含所有三个模型的所有记录的关系,因为:
join之外,您不能在不同的模型之间直接创建一个关系,然后就有了记录的混合。https://stackoverflow.com/questions/20685839
复制相似问题