【问题标题】:Rails: Favoriting System - models associationsRails:收藏系统 - 模型关联
【发布时间】: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


【解决方案1】:

目前尚不清楚为什么您同时拥有多态 favoritedproduct_id/variant_id 上的单独关系。通常人们会选择其中一种方法。 多态关联也可以是单向的 - has_many :favorites, as: :favorited, dependent: :destroy

如果您为每个关系使用单独的列 - product_idvariant_id 上的索引也可能有助于防止对产品/变体删除进行全表扫描(在 dependent: :destroy 上,如果您不期望回调/那里的嵌套关系 - delete_all 更快)。

【讨论】:

  • 感谢@Vasfed 的回复。所以你基本上是建议从迁移中删除product_id &amp; variant_id,并在产品和变体模型上用has_many :favorites, as: :favorited, dependent: :destroy替换这个has_many :favorites, dependent: :destroy?其他一切都保持不变?
猜你喜欢
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多