Ruby on rails rails迁移将外键移动到第三个联接模型

Ruby on rails rails迁移将外键移动到第三个联接模型,ruby-on-rails,activerecord,migration,database-schema,Ruby On Rails,Activerecord,Migration,Database Schema,我的车队管理rails应用程序有两种型号 class Location < ActiveRecord::Base has_many :fleets end class Fleet < ActiveRecord::Base belongs_to :location end 将迁移写入的最佳方式是什么- 从震源组中删除外键location\u id,同时填充分配表中的记录 将state列从fleets移动到allocations并填充它 如何在不破坏代码的情况下使这些迁移可逆

我的车队管理rails应用程序有两种型号

class Location < ActiveRecord::Base
  has_many :fleets
end

class Fleet < ActiveRecord::Base
  belongs_to :location
end
将迁移写入的最佳方式是什么-

  • 震源组
    中删除外键
    location\u id
    ,同时填充
    分配
    表中的记录
  • state
    列从
    fleets
    移动到
    allocations
    并填充它
  • 如何在不破坏代码的情况下使这些迁移可逆 按以下方式编写迁移是否好?或者我应该编写两个单独的迁移,一个创建
    分配并填充,另一个从
    震源组中删除列
    ?我是否遗漏了以下迁移中的任何关键内容

    def self.up 
      create_table :allotments do |t|
        t.references :fleet, index: true
        t.references :location, index: true
        t.string :state
      end
      Fleet.all.each do |f|
        l = f.location
        Allotment.create(fleet: f, location: l, state: f.state)
      end
      remove_reference :fleets, :location, index: true
      remove_column :fleets, :state
    end 
    self.down
      add_refrence :fleets, :location, index: true
      add_column :fleets, :state, :string
      Fleet.all.each do |f|
        f.update_column :state, f.allotments.first.state
        f.update_column :location_id, f.locations.first.id
      end
      drop_table :allotments
    end
    

    我在迁移中发现了一个问题。如果
    f.allotments.first
    self.down
    中返回nil,则它是不可逆的。我如何继续?在这里和那里读了很多书之后,我决定不在迁移中使用模型来更新/创建数据。有两件事:不要使用
    def self.up
    ,而是可以在迁移中使用模型,只要您自己在迁移类中重新定义类。
    def self.up 
      create_table :allotments do |t|
        t.references :fleet, index: true
        t.references :location, index: true
        t.string :state
      end
      Fleet.all.each do |f|
        l = f.location
        Allotment.create(fleet: f, location: l, state: f.state)
      end
      remove_reference :fleets, :location, index: true
      remove_column :fleets, :state
    end 
    self.down
      add_refrence :fleets, :location, index: true
      add_column :fleets, :state, :string
      Fleet.all.each do |f|
        f.update_column :state, f.allotments.first.state
        f.update_column :location_id, f.locations.first.id
      end
      drop_table :allotments
    end