更新一列的另一种价值的Rails迁移 [英] Update one column to value of another in Rails migration

查看:99
本文介绍了更新一列的另一种价值的Rails迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用程序数以十万计的记录的表,他们只有一个 created_at 时间戳。我添加编辑这些记录的能力,所以我想给的updated_at 时间戳添加到表中。在我迁移到添加列,我想更新所有行有新的的updated_at 匹配旧 created_at ,因为这是默认的Rails的新建行。我可以做一个找到(:所有)并遍历记录,但会采取,因为表的大小小时。我真正想要做的是:

I have a table in a Rails app with hundreds of thousands of records, and they only have a created_at timestamp. I'm adding the ability to edit these records, so I want to add an updated_at timestamp to the table. In my migration to add the column, I want to update all rows to have the new updated_at match the old created_at, since that's the default for newly created rows in Rails. I could do a find(:all) and iterate through the records, but that would take hours because of the size of the table. What I really want to do is:

UPDATE table_name SET updated_at = created_at;

有没有一种更好的方式来做到这一点在使用ActiveRecord的,而不是执行原始的SQL一个Rails迁移?

Is there a nicer way to do that in a Rails migration using ActiveRecord rather than executing raw SQL?

推荐答案

我想创建一个迁移

rails g migration set_updated_at_values

和里面写的是这样的:

class SetUpdatedAt < ActiveRecord::Migration
  def self.up
    Yourmodel.update_all("updated_at=created_at")
  end

  def self.down
  end
end

这样你实现两件事情

This way you achieve two things

  • 这是一个重复的过程,每一个可能的部署(如需要)被执行
  • 这是有效的。我想不出一个更rubyesque解决方案(即高效)。

请注意:您还可以运行原始的SQL迁移里面,如果查询变得太硬用ActiveRecord的编写。只写了以下内容:

Note: you could also run raw sql inside a migration, if the query gets too hard to write using activerecord. Just write the following:

    Yourmodel.connection.execute("update your_models set ... <complicated query> ...")

这篇关于更新一列的另一种价值的Rails迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆