假设我正在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正如您所看到的,手环和手表在一对多的情况下都依赖于材料,但是材料不关心或不需要知道手表或手环,所以belongs_to:不适合,也不适合多态关联
如何在rails 6中对此进行建模?那么迁移会是什么样子呢?
谢谢
发布于 2019-11-29 00:41:57
如下所示:
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你觉得这个决定怎么样?如果有什么不对劲,那就说出来。
https://stackoverflow.com/questions/59092384
复制相似问题