gpt4 book ai didi

ruby-on-rails - 规范化 rails 中的数据

转载 作者:行者123 更新时间:2023-12-01 07:31:42 24 4
gpt4 key购买 nike

我通过做创建了一个 rails 模型

script/generate model Customer name:string address:string city:string state:string zip:integer [...]

我用 5000 个客户填充了数据库并开始构建我的应用程序。现在我意识到我的模型没有标准化:我经常在同一个地址有多个客户!如果我想按地址做一些事情,比如邮寄,这会导致问题。我想要的是 Address 模型、 Customer 模型和 Mailing 模型。

是否有一种方法可以规范化现有模型,将其拆分为两个模型?或者我应该编写一个脚本来规范化现有数据,然后相应地生成新模型?

最佳答案

您询问了迁移会是什么样子。我没有将其塞进评论回复中,而是为您创建了一个新答案。
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

资源
  • AcitveRecord::Migration
  • execute
  • 关于ruby-on-rails - 规范化 rails 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2627186/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com