Rails 这种情况下应该怎么用 Polymorphic Associations

slim · 2016年03月28日 · 最后由 leomayleomay 回复于 2016年03月30日 · 2399 次阅读

我现在有 Product 和 Image 两个 Model。Product 有三种图片:feature image,gallery image,description image。两个 Model 的主要属性如下:

Product

  • id
  • title
  • price

Image

  • id
  • title
  • url
  • imageable_id
  • imageable_type

我是想用 imageable_type 来区分三种不同类型的图片。请问这种情况下应该怎么用 Polymorphic Associations 把两个 Model 关联起来? 这样设计表的目的也是为了以后如果有另外的 Model 需要图片,也可以用这个 Image 类。

Image 再加一个 image_type 字段,然后使用 Enum 就可以了啊

你的 images 表设计有点问题,去掉imageable_typeimageable_id, 加上type, 可以用 STI (Single Table Inheritance),

class FeatureImage < Image
end

class GalleryImage < Image
end

class DescriptionImage < Image
end

class Product
  has_many :feature_images
  has_many :gallery_images
  has_many :description_images
end

这种情况貌似不能用官方给的 Polymorphic Associations 来做。可以用下面的方式来写:

class Product < ActiveRecord::Base
  has_many :gallery_images, -> { where imageable_type: :product_gallery },
           class_name: 'Image', foreign_key: :imageable_id

  has_many :description_images, -> { where imageable_type: :product_description },
           class_name: 'Image', foreign_key: :imageable_id
end

这样写了之后不知道 Fixture 里面怎么写。

#3 楼 @leomayleomay Image 表里面还是需要有个外键吧?

@slim Image 属于谁,需要一个外键来指定啊

需要 登录 后方可回复, 如果你还没有账号请 注册新账号