Search and update activerecord

Is there a find_and_update method on ActiveRecord :: Base that basically finds the record by this identifier and updates the given key? This avoids the request and then updates, resulting in 2 requests instead of 1.

thanks

+4
source share
2 answers

The active record has an update method that finds by identifiers and updates attributes. But this will cause two sql queries.

update(id, attributes) 

eg,

  Post.update(params[:id], {:title => 'Hello world'}) 

If you do not want the checks to be performed, you can use

 Post.update_all({:title => 'hello1'}, {:id => params[:id]}) 

This will make only one sql request

+5
source
 User.where(id: id).update_all(foo: bar) 

This generates only one request.

0
source

All Articles