首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Active Record - Rails 6,具有两个不相关模型使用的模型

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

Stack Overflow用户
提问于 2019-11-28 23:47:17
回答 1查看 88关注 0票数 1

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

模型应该是这样的:

代码语言:javascript
复制
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中对此进行建模?那么迁移会是什么样子呢?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-29 00:41:57

如下所示:

代码语言:javascript
复制
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

你觉得这个决定怎么样?如果有什么不对劲,那就说出来。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59092384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档