问题
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