开发者

rails 3, new model B is 1:1 with old model A, how to auto create new B record for each already-existing A record

Rails v3.0.3 Original schema has 开发者_StackOverflow中文版customers table, and the app has data for 100 customers.

via migration we add cust_info table with 1:1, eg:

customers has_one cust_info 
cust_info belongs_to customers

so right now (after running rake db:migrate to create the new model) we have 100 'old' customer records that do not have the 1:1 required cust_info record.

QUES (1a) (legacy data update) what is the "rails way" to generate the required (empty) cust_info record for each of our 100 existing customer records?

QUES (2) (going forward) how to we modify our app so when we create a NEW customer record it will automatically create an associated cust_info record at the same time?


Q1: Because you've a small dataset, I'd work in the console:

Customer.all.each do |c|
   c.create_cust_info.save
end

Q2: use the following callback: after_create in your customer model and build the cust_info inside

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜