Using update_columns in Rails 3?

2020-06-09 04:12发布

问题:

Is there a shorter way for this in Rails 3?

user.update_column(:attribute1, value1)
user.update_column(:attribute2, value2)
user.update_column(:attribute3, value3)
user.update_column(:attribute4, value4)

I tried update_columns but it's only available in Rails 4.

Thanks for any help.

回答1:

Here's a workaround for Rails 3.x:

User.where(id: user.id).update_all(attribute1: value1, attribute2: value2, ...)


回答2:

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.



回答3:

another approach you can take which accomplishes the same thing is this:

user.assign_attributes(
  first_name: 'foo',
  last_name: 'bar'
)

user.save(validate: false)

NOTE: You don't have to use the validate false. However, the #update_column method does skip validations and callbacks. So if that is what you are looking for, use the validate false.