Ruby-on-rails 我如何在条件中执行更新语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9186822/
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 02:46:50  来源:igfitidea点击:

How do i do an update statement where a condition

ruby-on-railsruby-on-rails-3

提问by Matt Elhotiby

In Rails 3, how do I update an attribute with a condition like:

在 Rails 3 中,如何使用以下条件更新属性:

Model.where("state == 'decline'").all.update_attribute(:state, 'deny')

This is definitely wrong, but I am drawing a blank on how to achieve this.

这绝对是错误的,但我对如何实现这一目标一无所知。

回答by Bradley Priest

ActiveRecord::Relationsupplies an update_allmethod.

ActiveRecord::Relation提供了一个update_all方法。

Model.where(state: 'decline').update_all(state: 'deny')

回答by Kris

You can also chain update_alloff a scope such as:

您还可以链接update_all一个范围,例如:

book.chapters.where(state: 'draft').update_all(state: 'unpublished')