ruby-on-rails - STI 多态 has_many 使用错误的类型值

标签 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

在 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. The class_name of the attachable is passed as a 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

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

所以它说,您不需要存储 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/

相关文章:

doctrine - Doctrine 2 中的多态关联?

ruby-on-rails - 没有要加载的文件 -- rdoc/task

ruby-on-rails - 无法在 Rails 3 中找到 has_many 的逆关联

ruby-on-rails - 在 Rails 中为多态关联创建表单

database - 一组外键,其中除了一个外都是 NULL

ruby-on-rails - 如何更改现有的评论模型,使其可以属于许多不同的模型?

ruby-on-rails - Join Tables 中的嵌套关​​系 - Rails

ruby-on-rails - 最新的 Active_Model_Serializers 打破了 Devise Views

ruby-on-rails - rails 3.0 : error with routes when overriding to_param in model

ruby-on-rails - Ruby on Rails form_tag - 将模型参数发送到 Controller