如何在Ruby on Rails 3中更新多个列?

15

只是出于好奇,有没有一种方法来表达这个意思...

user.update_column(:field1, true)
user.update_column(:field2, true)

在Ruby on Rails中,有没有一行代码实现更新?

据我所知,update_columns方法不存在...

4个回答

45
你可以按照以下方式使用update_all
User.where(:id => user.id).update_all({:field1 => true, :field2 => true})

这将生成以下更新语句(mysql):

UPDATE users SET field1 = 1, field2 = 1 WHERE users.id = <whatever>

回调函数和验证将不会运行。


如果您的目标是在不更改updated_at字段的情况下更新记录,则这将无法实现。否则,这是正确的方法。 - Adam Grant

4

注意:此功能仅在ActiveRecord v4.0.2及更高版本中可用:

您可以这样做:

update_columns(field1: value, filed2: value)

3
这仅在ActiveRecord v4.0.2及更高版本中可用: http://apidock.com/rails/ActiveRecord/Persistence/update_columns - ckbhodge
1
这个仅更新单条记录,不像update_all那样更新updated_at和回调。 - carbonr

2
像这样做怎么样:
user.attributes = attributes
user.save(validate: false)

0
如果您需要速度,您也可以直接在AR连接上调用execute。我曾经使用类似的方法导入大量数据。
connection = ActiveRecord::Base.connection
email = connection.quote(email)
zip = connection.quote(zip)
connection.execute(%{UPDATE "users" SET "email" = #{email}, "zip" = #{zip} WHERE "users"."id" = #{user.id}})

请注意,验证和回调将不会运行。
https://dev59.com/FmMl5IYBdhLWcg3wknwT#25171127复制。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接