How to update multiple columns in Ruby on Rails 3?

笑着哭i 提交于 2019-12-08 14:55:58

问题


Just out of curiosity, is there a way to say this...

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

... in one line in Ruby on Rails?

As far as I know an update_columns method does not exist...


回答1:


You can use update_all as follows:

User.where(:id => user.id).update_all({:field1 => true, :field2 => true})

This will generate the following update statement (mysql):

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

Callbacks and validations will not be run.




回答2:


what about doing it like this:

user.attributes = attributes
user.save(validate: false)



回答3:


You can do in this way:

update_columns(field1: value, filed2: value)



回答4:


If you need speed you can also call execute directly on AR connection. I used something like this to import large amount of data.

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}})

Note that validations and callbacks will not be run.

Copied from https://stackoverflow.com/a/25171127/1520775



来源:https://stackoverflow.com/questions/14880931/how-to-update-multiple-columns-in-ruby-on-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!