且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Rails 迁移中将一列更新为另一列的值

更新时间:2022-03-14 21:55:31

我会创建一个迁移

rails g migration set_updated_at_values

在里面写一些类似的东西:

and inside it write something like:

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

  def self.down
  end
end

这样你就实现了两件事

  • 这是一个可重复的过程,每个可能的部署(在需要的地方)都会执行
  • 这很有效率.我想不出更像红宝石般的解决方案(效率一样高).

注意:如果使用 activerecord 编写查询太难,您也可以在迁移中运行原始 sql.只需编写以下内容:

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> ...")