Reputation: 21553
Is there a method find_and_update method on ActiveRecord::Base that will basically find a record by it's id and update a given key? This will avoid having to query and then update resulting in 2 queries instead of 1.
Thanks
Upvotes: 7
Views: 10531
Reputation: 61
User.where(id: id).update_all(foo: bar)
This generates only one query.
Upvotes: 6
Reputation:
There is an update method in active record, which finds by id and updates attributes. But this will make two sql queries.
update(id, attributes)
eg
Post.update(params[:id], {:title => 'Hello world'})
If you dont want validations to happen, you could use
Post.update_all({:title => 'hello1'}, {:id => params[:id]})
This will make only one sql query
Upvotes: 10