【问题标题】:Does Rails automatically wrap non-schema-change migrations in a transaction?Rails 是否会自动将非模式更改迁移包装在事务中?
【发布时间】:2022-03-30 23:09:16
【问题描述】:

我在 Rails 应用程序中创建了迁移:

class UpdateDefaultValues < ActiveRecord::Migration[5.2]
  def up
    OrderType.where(:category =>"reclamation").update_all(:prevent_delivery => false)
    InvoiceType.where(:category =>"reclamation").update_all(:send_automatically => true)
  end

  def down
    OrderType.where(:category =>"reclamation").update_all(:prevent_delivery => true)
    InvoiceType.where(:category =>"reclamation").update_all(:send_automatically => false)
  end
end

值得注意的是,此迁移不会更改数据库架构;它只执行数据更改。

我想知道:rails 是否自动在 SQL 事务中执行 updown 方法,还是我需要将这两个更新包装在自己的事务中,以确保迁移是全部更新还是什么都不更新?

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

Rails 不会将其放入事务块中。如果其中一个失败,它将退出。如果您无论如何都希望两者都发生,那么正如您所说,您将不得不放入一个ActiveRecord::Base.transaction 块。在您的情况下,它应该如下所示 -

class UpdateDefaultValues < ActiveRecord::Migration[5.2]
  def up
    ActiveRecord::Base.transaction do
      OrderType.where(:category =>"reclamation").update_all(:prevent_delivery => false)
      InvoiceType.where(:category =>"reclamation").update_all(:send_automatically => true)
    end
  end

  def down
    ActiveRecord::Base.transaction do
      OrderType.where(:category =>"reclamation").update_all(:prevent_delivery => true)
      InvoiceType.where(:category =>"reclamation").update_all(:send_automatically => false)
    end
  end
end

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 2012-11-07
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2019-03-09
    • 2021-05-04
    相关资源
    最近更新 更多