Update multiple records simultaneously with ActiveRecord in Rails using one query?

情到浓时终转凉″ 提交于 2019-12-31 21:59:19

问题


Let's suppose I have a table called 'user_products' and a corresponding model called UserProduct in my Rails application. I also have a field called 'is_temporary' in my table. Now suppose I want to run a query like this but using the ActiveRecord abstraction layer:

UPDATE user_products SET is_temporary = false WHERE user_id = 12345;

Is there a way I can do this using ActiveRecord? Maybe something along the lines of

UserProduct.find_by_user_id(12345).update_attributes(:is_temporary => false)

I'd like only one query to be run for this to happen.


回答1:


UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})



回答2:


This is an old post. I updated this in case someone checks it :) (Rails 4)

DEPRECATION: Relation#update_all with conditions is deprecated. Please use Item.where(color: 'red').update_all(...) rather than Item.update_all(..., color: 'red').

So the query will be

UserProduct.where(:user_id => 12345).update_all(:is_temporary => false)

Cheers




回答3:


UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})

Although beware: this skips all validations and callbacks, since no instance of UserProduct will ever be instanciated.



来源:https://stackoverflow.com/questions/4455479/update-multiple-records-simultaneously-with-activerecord-in-rails-using-one-quer

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