2010-12-15 56 views
14

假设我在我的Rails应用程序中有一个名为'user_products'的表和一个名为UserProduct的对应模型。我的桌子上也有一个名为'is_temporary'的字段。现在假设我想运行这样的查询,但使用ActiveRecord的抽象层:使用一个查询在Rails中与ActiveRecord同时更新多个记录?

UPDATE user_products SET is_temporary = false WHERE user_id = 12345; 

有没有一种方法,我可以做到这一点使用ActiveRecord?也许沿线的东西

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

我想只有一个查询运行,为此发生。

回答

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

虽然提防:此跳过所有验证和回调,因为没有UserProduct的情况下都不会被实例化。

19

这是一个旧帖子。我的情况下,更新了这个有人检查它:)(轨道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) 

干杯

+1

非常感谢,谢谢! – Sebastialonso 2014-05-12 06:14:39

+0

这似乎也适用于Rails 3 – lavaturtle 2015-07-22 18:57:48

相关问题