STI 多态 has_many 使用错误的类型值

Ari*_*dam 2 ruby-on-rails polymorphic-associations

我有以下 STI 模型,它们具有多态关联,其查询构造错误

class Product < ApplicationRecord
  has_many :images, as: :imageable
end

class OneProduct < Product
end

class Image < ApplicationRecord
  belongs_to :imageable
end
Run Code Online (Sandbox Code Playgroud)

在 Rails 控制台中,当我这样做时

> OneProduct.last.icon_images
Run Code Online (Sandbox Code Playgroud)

被触发的查询是

SELECT  * FROM images WHERE imageable_id = id AND imageable_type = 'Product'
Run Code Online (Sandbox Code Playgroud)

我期待着:

SELECT * from images WHERE imageable_id = id AND imageable_type = 'OneProduct'
Run Code Online (Sandbox Code Playgroud)

我期待有什么不对吗?

侧面信息:数据库是 postgres。

Dee*_*eep 6

来自 Rails 文档:

将多态关联与单表继承 (STI) 结合使用有点棘手。为了使关联按预期工作,请确保将 STI 模型的基本模型存储在多态关联的类型列中。为了继续上面的资产示例,假设有访客帖子和成员帖子使用 STI 的 posts 表。在这种情况下,posts 表中必须有一个 type 列。

注意:attachable_type= method分配可附加项时将调用。可附加的的class_name作为 传递String

class Asset < ActiveRecord::Base   
  belongs_to :attachable, polymorphic: true

  def attachable_type=(class_name)
     super(class_name.constantize.base_class.to_s)   
  end 
end

class Post < ActiveRecord::Base   
  # because we store "Post" in attachable_type now dependent: :destroy will work   
  has_many :assets,as: :attachable, dependent: :destroy 
end

class GuestPost < Post end

class MemberPost < Post end
Run Code Online (Sandbox Code Playgroud)

来源: https ://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations

所以它说,imageable_type = OneProduct您不需要将其存储为Product仅,并且可以type在表中添加一列Product。但这完全取决于您需要从模型中获得什么OneProduct,如果default_scope该模型上的某个功能可以在不添加列的情况下为您工作,type那么就不要将其添加到表中Product,如果这不起作用,那么您可以添加列并然后在模型上查询时添加default_scopefetch 。products.type = OneProductOneProduct