使用一个查询在Rails中同时使用ActiveRecord更新多个记录?

假设我的Rails应用程序中有一个名为“user_products”的表和一个名为UserProduct的对应模型。 我的表中还有一个名为’is_temporary’的字段。 现在假设我想运行这样的查询,但使用ActiveRecord抽象层:

UPDATE user_products SET is_temporary = false WHERE user_id = 12345; 

有没有办法使用ActiveRecord做到这一点? 也许有些事情

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

我想只运行一个查询才能实现。

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

这是一个老post。 如果有人检查它我更新了这个:)(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'). 

所以查询将是

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

干杯

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

虽然要注意:这会跳过所有validation和回调,因为不会实例化UserProduct的实例。