您将遇到一些命名空间问题,因为您的新域关联需要进行一些重命名。迁移也可以运行 ruby 代码,因此您的迁移可能看起来像这样
以下是所需的通用代码。
# First Migration to rename the domain field
def RenameDomainField < ActiveRecord::Migration
def self.up
rename_column :domain_datas, :domain, :domain_name
end
def self.down
#code for opposite of up
end
end
# Second Migration to add the Domain model
def CreateDomains < ActiveRecord::Migration
def self.up
create_table :domain do |t|
t.string :domain_name
end
end
def self.down
#code for opposite of up
end
end
#Create a new relationship:
def DomainData < ActiveRecord::Base
belongs_to :domain
end
# A third migration to move the data over
def RefactorDomainData < ActiveRecord::Migration
def self.up
#Add the new forgein key
add_column :domain_datas, :domain_id, :integer
#create the new domain records and link them
DomainData.all do |domain_data|
domain_data.create_domain(:domain_name => domain_data.domain_name)
end
#trash the old column
remove_column :domain_datas, :domain_name
end
def self.down
#code for opposite of up
end
end