我有以下 STI 模型,它们具有多态关联,其查询构造错误
class Product < ApplicationRecord
has_many :images, as: :imageable
end
class OneProduct < Product
end
class Image < ApplicationRecord
belongs_to :imageable
end
在 Rails 控制台中,当我这样做时
> OneProduct.last.icon_images
被触发的查询是
SELECT * FROM images WHERE imageable_id = id AND imageable_type = 'Product'
我期待的是:
SELECT * from images WHERE imageable_id = id AND imageable_type = 'OneProduct'
我期待有什么问题吗?
辅助信息:数据库是 postgres。
最佳答案
来自 Rails 文档:
Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order for the associations to work as expected, ensure that you store the base model for the STI models in the type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts and member posts that use the posts table for STI. In this case, there must be a type column in the posts table.
Note: The
attachable_type= method
is being called when assigning an attachable. Theclass_name
of the attachable is passed as aString
.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
所以它说,您不需要存储 imageable_type = OneProduct
您只需将其存储为 Product
并且您可以添加 type
列在 Product
表中。但这完全取决于您对 OneProduct
模型的需求,如果该模型上的 default_scope
可以使其在不添加 type
的情况下为您工作列,然后不要将其添加到 Product
表中,如果这不起作用,那么您可以添加该列,然后添加 default_scope
来获取 产品。在
。OneProduct
模型上查询时,type = OneProduct
关于ruby-on-rails - STI 多态 has_many 使用错误的类型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56835369/