【问题标题】:Rails migration to update database table_one with data from related tableRails 迁移以使用相关表中的数据更新数据库 table_one
【发布时间】:2014-11-08 16:37:43
【问题描述】:

我有两张桌子。 Table_1 与 table_2 具有一对多的关系。我的目标是使用 rails 迁移将 table_2 中的所有数据移动到 table_1 中新创建的文本列。 我将在使用 sqlite 的迁移中执行以下操作。

def up
 sql = "UPDATE table_1 SET column=(SELECT name || ' ' || email FROM       
 table_2 WHERE table2.table_1_id=table_1.id)"
 update (sql)
end 

这可行,但问题是,table_1 中的每条记录在 table_2 中都有 1 个或多个相关记录,如何将 table_1 中的字段设置为 table_2 中的所有相关记录

【问题讨论】:

    标签: sql ruby-on-rails migration


    【解决方案1】:

    我会编写一个自定义种子文件并通过 rake 任务运行它以执行诸如此类的数据任务,并使用此处答案中建议的实现:

    Adding a custom seed file

    由于它是一个 rb 文件,您可以使用标准模型/循环/活动记录 Rails 代码,这应该可以更简单地维护关联等。

    【讨论】:

      【解决方案2】:

      最好的选择是在您的迁移中,除了创建新表的代码之外,添加代码以将旧表中的数据“导入”到新表中。之后,如果旧表不相关,您可以删除它们。

        def up
          add_column :table1, :newfield, :string
      
          Table1.all.each do |record|
            record.newfield = record.relation.fields
            record.save!
        end
      
      # Beware that if you need to rollback, it's better to implement a way 
      # to revert the changes.
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        • 1970-01-01
        • 2017-05-26
        • 2012-04-11
        相关资源
        最近更新 更多