rails migration将外键移动到第三个连接模型

时间:2016-04-14 05:16:44

标签: ruby-on-rails activerecord migration database-schema

我的车队管理rails app有两种型号

class Location < ActiveRecord::Base
  has_many :fleets
end

class Fleet < ActiveRecord::Base
  belongs_to :location
end

fleets表的location_id为外键,state列表示fleet的状态(active,inactive,new)。现在我想编写迁移以将此关系移动到名为Allotment的第三个模型中。我的模型看起来应该是这样的

class Location < ActiveRecord::Base
  has_many :allotments
  has_many :fleets, :through => :allotments
end
class Fleet < ActiveRecord::Base
  has_many :allotments
  has_many :branches, :through => :allotments
end
class Allotment < ActiveRecord::Base
  belongs_to :fleet
  belongs_to :location
end

将迁移编写到 -

的最佳方法是什么
  1. location_id中删除外键fleets并同时填充allotments表中的记录。
  2. state列从fleets移至allotments并填充
  3. 如何在不破坏代码的情况下使这些迁移可逆。
  4. 如下编写迁移是否合适?或者我应该编写两个单独的迁移,一个用于创建allotments并填充它,另一个用于从fleets删除列?我错过了以下迁移中的任何重要内容吗?

    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
    

0 个答案:

没有答案