Active Record - Rails 6, 有两个不相关模型使用的模型

Active Record - Rails 6, Having a model that two unrelated models use

假设我在 rails 6 中构建了一个手表分类器系统。我有一个名为 material 的模型,material 由表体和手链使用。

模型应该是这样的:

Material:
    description - text (gold, platinum, steel, silver etc)

Bracelet:
    style - text
    Material - has_many references (could be silver and rose gold etc)
    clasp - text
    etc

Watch
    brand - text
    Material - has_many references (case could be gold & white Gold etc)
    etc

如您所见,Bracelet 和 Watch 都依赖于一对多的 material,但 material 不关心或不需要了解 Watch 或 Bracelet,因此 belongs_to : 不适合,多态关联也不适合

如何在 rails 6 中建模?迁移会是什么样子?

谢谢

像这样:

class CreateMaterials < ActiveRecord::Migration[6.0]
  def change
    create_table :materials do |t|
      t.integer :description, default: 0

      t.timestamps
    end
  end
end

class Material < ApplicationRecord
  enum description: %i[gold, platinum, steel, silver] # etc

  has_and_belongs_to_many :watches
  has_and_belongs_to_many :bracelets
end





class CreateBracelets < ActiveRecord::Migration[6.0]
  def change
    create_table :bracelets do |t|
      t.text :style
      t.text :clasp
      # etc

      t.timestamps
    end
  end
end

class Bracelet < ApplicationRecord
  has_and_belongs_to_many :materials
end




class CreateWatches < ActiveRecord::Migration[6.0]
  def change
    create_table :watches do |t|
      t.text :brand
      # etc

      t.timestamps
    end
  end
end

class Watch < ApplicationRecord
  has_and_belongs_to_many :materials
end




class CreateMaterialsBracelets < ActiveRecord::Migration[6.0]
  def change
    create_table :materials_bracelets, id: false do |t|
      t.belongs_to :material, foreign_key: true
      t.belongs_to :bracelet, foreign_key: true
    end
  end
end

class CreateMaterialsWatches < ActiveRecord::Migration[6.0]
  def change
    create_table :materials_watches, id: false do |t|
      t.belongs_to :material, foreign_key: true
      t.belongs_to :watch, foreign_key: true
    end
  end
end

你觉得这个决定怎么样?有什么不对的地方再说。