【发布时间】:2021-01-15 08:24:24
【问题描述】:
我有以下模型关联设置,消费者可以喜欢产品或变体。我只是想问一下我的做法是否正确?
class Favorite < ApplicationRecord
belongs_to :consumer
belongs_to :favorited, polymorphic: true
belongs_to :product, optional: true
belongs_to :variant, optional: true
end
class Consumer < ApplicationRecord
has_many :favorites
has_many :favorite_products, through: :favorites, source: :favorited, source_type: 'Product'
has_many :favorite_variants, through: :favorites, source: :favorited, source_type: 'Variant'
end
class Product < ApplicationRecord
has_many :favorites, dependent: :destroy
end
class Variant < ApplicationRecord
has_many :favorites, dependent: :destroy
end
class CreateFavorites < ActiveRecord::Migration[6.0]
def change
create_table :favorites do |t|
t.references :consumer, index: true
t.references :favorited, polymorphic: true, index: true
t.integer :product_id
t.integer :variant_id
t.timestamps
end
end
end
【问题讨论】:
-
看看这个schmidt-happens.com/articles/2014/06/04/…。它可能会帮助你!
-
感谢@Theopap 的帮助。我已经读过这个了。基于此设置,我创建了模型关联。但就我而言,我有产品和变体,而不是项目。仍然不确定我想出的方法是否正确。如果我的模型关联正确,有什么想法吗?
标签: ruby-on-rails ruby-on-rails-5