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

时间:2010-12-15 22:11:50

标签: ruby-on-rails orm 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)

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

3 个答案:

答案 0 :(得分:19)

这是一篇旧帖子。如果有人检查它,我更新了这个:)(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)

干杯

答案 1 :(得分:18)

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

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

答案 2 :(得分:16)

UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
相关问题