Using update_columns in Rails 3?

和自甴很熟 提交于 2019-12-12 07:44:43

问题


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.



来源:https://stackoverflow.com/questions/18291071/using-update-columns-in-rails-3

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