Ruby-on-rails Rails 3 + activerecord,为所有满足条件的记录“批量更新”单个字段的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4912510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:20:43  来源:igfitidea点击:

Rails 3 + activerecord, the best way to "mass update" a single field for all the records that meet a condition

ruby-on-railsactiverecord

提问by jpw

In rails 3, using activerecord, is there a single-query way to set the :hiddenfield to TRUEfor all records that meet a condition ... say, for example, :condition => [ "phonenum = ?", some_phone_number ]

在 rails 3 中,使用 activerecord,是否有一种单查询方法可以将所有满足条件的记录的:hidden字段设置为TRUE......例如,:condition => [ "phonenum = ?", some_phone_number ]

If a single query cannot do it, what IS the optimal approach?

如果单个查询无法完成,最佳方法是什么?

回答by Dogbert

Use update_allwith the optional second parameter for the condition:

update_all与可选的第二个参数一起用于条件:

Model.update_all({ hidden: true }, { phonenum: some_phone_number})

回答by Deepak N

The update_all does not allow conditions in rails 3. You can use combination of scope and update_all

update_all 不允许 rails 3 中的条件。您可以使用 scope 和 update_all 的组合

Model.where(phonenum: some_phone_number).update_all(hidden: true)

Reference: http://m.onkey.org/active-record-query-interface

参考:http: //m.onkey.org/active-record-query-interface

回答by Dorian

If you want to trigger callbacks:

如果要触发回调:

class ActiveRecord::Base
  def self.update_each(updates)
    find_each { |model| model.update(updates) }
  end

  def self.update_each!(updates)
    find_each { |model| model.update!(updates) }
  end
end

Then:

然后:

Model.where(phonenum: some_phone_number).update_each(hidden: true)