14

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.

3 Answers 3

19

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to pass array in update_all, to make one to one corresponding update like. UserProduct.where(:user_id => [1,2,3,4,5]).update_all(:name => ["ball", "bat", "shelf", "boots", "net"]).
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.

Comments

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

1 Comment

This is deprecated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.