【问题标题】:Active Record - Rails 6, Having a model that two unrelated models useActive Record - Rails 6,拥有两个不相关模型使用的模型
【发布时间】:2019-11-28 15:47:16
【问题描述】:

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

模型应该是这样的:

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 都以一对多方式依赖于材料,但材料并不关心或不需要了解 Watch 或 Bracelet 所以belongs_to: 不适合,多态关联也不适合

如何在 Rails 6 中对此进行建模?迁移会是什么样子?

谢谢

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord ruby-on-rails-6


    【解决方案1】:

    类似这样的:

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      相关资源
      最近更新 更多