如何在条件中执行更新语句

Mat*_*iby 17 ruby-on-rails ruby-on-rails-3

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

Model.where("state == 'decline'").all.update_attribute(:state, 'deny')
Run Code Online (Sandbox Code Playgroud)

这绝对是错误的,但我在如何实现这一点上画了一个空白.

Bra*_*est 40

ActiveRecord :: Relation提供了一种update_all方法.

Model.where(state: 'decline').update_all(state: 'deny')
Run Code Online (Sandbox Code Playgroud)


Kri*_*ris 8

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

book.chapters.where(state: 'draft').update_all(state: 'unpublished')
Run Code Online (Sandbox Code Playgroud)