ruby-on-rails – 规范化rails中的数据
发布时间:2020-12-17 01:44:16 所属栏目:百科 来源:网络整理
导读:我做了一个rails模型 script/generate model Customer name:string address:string city:string state:string zip:integer [...] 我用5000个客户填充了数据库并开始构建我的应用程序.现在我意识到我的模型没有规范化:我经常在同一个地址有多个客户!如果我
我做了一个rails模型
script/generate model Customer name:string address:string city:string state:string zip:integer [...] 我用5000个客户填充了数据库并开始构建我的应用程序.现在我意识到我的模型没有规范化:我经常在同一个地址有多个客户!如果我希望按地址执行某些操作,例如邮件,则会导致问题.我想要的是地址模型,客户模型和邮件模型. 是否有轨道方式来规范现有模型,将其分为两个模型?或者我应该编写一个脚本来规范化现有数据,然后相应地生成新模型? 解决方法
您询问了迁移的样子.我没有在评论回复中填写此内容,而是为您创建了一个新答案.
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |