我通过
创建了一个rails模型script/generate model Customer name:string address:string city:string state:string zip:integer [...]
我用5000个客户填充数据库并开始构建我的应用程序。现在我意识到我的模型没有规范化:我经常在同一个地址有多个客户!如果我希望按地址执行某些操作,例如邮件,则会导致问题。我想要的是Address
模型,Customer
模型和Mailing
模型。
是否有轨道方式来规范现有模型,将其拆分为两个模型?或者我应该编写一个脚本来规范化现有数据,然后相应地生成新模型吗?
答案 0 :(得分:8)
您询问了迁移的样子。我没有在评论回复中填写此内容,而是为您创建了一个新答案。
script/generate model address customer_id:integer address:string city:string state:string zip:integer
class CreateAddresses < ActiveRecord::Migration
def self.up
create_table :addresses do |t|
t.integer :customer_id
t.string :address
t.string :city
t.string :state
t.integer :zip_code
t.timestamps
end
# move customer address fields to address table
Customer.all.each do |c|
Address.create({
:customer_id => c.id,
:address => c.address,
:city => c.city,
:state => c.state,
:zip => c.zip
})
end
# you'll have to write your own merge script here
# use execute("your sql goes here...") if you can't do it with ActiveRecord methods
# remove old customer address columns
remove_columns(:customers, :address, :city, :state, :zip)
end
def self.down
# here you will define the reverse of the self.up method
# re-add the address columns to the user table
# repopulate the customer table with data from the address table
drop_table :addresses
end
end
答案 1 :(得分:4)
我不知道内置的Rails方式以编程方式拆分模型。您需要编写一个新的Address
模型和数据库更新迁移,以便切换所有内容。
您的模型可能看起来像这样:
class Person < ActiveRecord::Base
has_many :addresses
end
class Address < ActiveRecord::Base
belongs_to :person
end