我的车队管理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
将迁移编写到 -
的最佳方法是什么location_id
中删除外键fleets
并同时填充allotments
表中的记录。 state
列从fleets
移至allotments
并填充如下编写迁移是否合适?或者我应该编写两个单独的迁移,一个用于创建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