【问题标题】:rails 3, new model B is 1:1 with old model A, how to auto create new B record for each already-existing A recordrails 3,新模型 B 与旧模型 A 1:1,如何为每个已经存在的 A 记录自动创建新的 B 记录
【发布时间】:2011-02-02 23:01:29
【问题描述】:

Rails v3.0.3 原始架构有 customers 表,该应用有 100 个客户的数据。

通过迁移,我们以 1:1 添加 cust_info 表,例如:

customers has_one cust_info 
cust_info belongs_to customers

所以现在(在运行 rake db:migrate 以创建新模型之后)我们有 100 条“旧”customer 记录不具备所需的 1:1 cust_info记录。

QUES (1a)(旧数据更新)为我们现有的 100 个 customer 记录中的每一个生成所需(空)cust_info 记录的“rails 方式”是什么?

问题 (2)(未来)我们如何修改我们的应用程序,以便当我们创建新的 customer 记录时,它会同时自动创建关联的 cust_info 记录时间?

【问题讨论】:

    标签: ruby-on-rails model model-associations


    【解决方案1】:

    Q1:因为你的数据集很小,我会在控制台中工作:

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

    Q2:在您的客户模型中使用以下回调:after_create 并在内部构建 cust_info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      相关资源
      最近更新 更多