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:
假设我的Rails应用程序中有一个名为“user_products”的表和一个名为UserProduct的对应模型。我的表中还有一个名为'is_temporary'的字段。现在假设我想运行这样的查询,但使用ActiveRecord抽象层:
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
有没有办法使用ActiveRecord做到这一点?也许有些事情
UserProduct.find_by_user_id(12345).update_attributes(:is_temporary => false)
I'd like only one query to be run for this to happen.
我想只运行一个查询才能实现。
3 个解决方案
#1
16
UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
#2
19
This is an old post. I updated this in case someone checks it :) (Rails 4)
这是一个老帖子。如果有人检查它我更新了这个:)(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
18
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.
虽然要注意:这会跳过所有验证和回调,因为不会实例化UserProduct的实例。
#1
16
UserProduct.update_all({:is_temporary => false}, {:user_id => 12345})
#2
19
This is an old post. I updated this in case someone checks it :) (Rails 4)
这是一个老帖子。如果有人检查它我更新了这个:)(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
18
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.
虽然要注意:这会跳过所有验证和回调,因为不会实例化UserProduct的实例。