按类型选择多态外键



我在 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations 的模具中有一个简单的多态关联

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end

我想要的是抓取所有imageable_typeProduct的图片,例如。

Picture.imageable.where(imageable_type: "Product")有效,但这似乎并不理想。它需要知道类型列中的值。是否有直接指定模型的活动记录方法?例如,像这样:

Picture.imageable.where(imageable: Product)(其中产品是活动记录模型(

如果您打算使用 Product 而不是 "Product" 以便您可以捕获代码问题或拼写错误,那么您只需执行以下操作

即可
Picture.where(imageable_type: Product.to_s)
# will run fine
Picture.where(imageable_type: Produkt.to_s)
# will raise an error as it is a typo

顺便说一句,我想我听不懂你说的

它需要知道类型列中的值

因为您想要的.where(imageable: Product)仍然需要提供值

琐事

Picture.where(imageable: Product)

。已经实现,但您不应该这样使用它,而是以下:

product1 = Product.first
product1_pictures = Picture.where(imageable: product1)

employee1 = Employee.first
employee1_pictures = Picture.where(imageable: employee1)

最新更新