Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return value of update_all() in ActiveRecord / Ruby on Rails?

The Ruby on Rails and ActiveRecord documentation, Google, and StackOverflow are conspiratorially silent on the return value of update_all()

What does update_all() return?

  • Number of records?
  • Success status?
  • ID's of updated records?
like image 774
David Hempy Avatar asked Sep 05 '18 15:09

David Hempy


People also ask

Where can I find discussion about Ruby on rails documentation?

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list . "Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson.

Is it possible to add keys to conditions in Ruby on rails?

For more information on the dangers of SQL injection, see the Ruby on Rails Security Guide. Similar to the (?) replacement style of params, you can also specify keys in your conditions string along with a corresponding keys/values hash:

Where are rails active record migrations stored?

Migrations are stored in files which are executed against any database that Active Record supports using rake. Here's a migration that creates a table: Rails keeps track of which files have been committed to the database and provides rollback features.

How do you return the last executed instruction in Ruby?

when return isn’t explicitly called within a method then Ruby returns the value of the last executed instruction in the method In the implicit_return method, as if true is always evaluated as true (mister obvious) then the last executed instruction is 42.


2 Answers

ActiveRecord's update_all() returns the number of records updated.

describe '.update_all' do
  let!(:user1) { create :user, last_name: 'Smitty' }
  let!(:user2) { create :user, last_name: 'Smitty' }
  let!(:user3) { create :user, last_name: 'Doe' }

  it 'returns number of records updated' do
    expect(User.where(last_name: 'Smitty')
               .update_all(last_name: 'Smith')).to eq 2
  end
end

Yields:

User
  .update_all
    returns number of records updated

Finished in 0.1245 seconds (files took 13.17 seconds to load)
1 example, 0 failures
like image 153
David Hempy Avatar answered Oct 22 '22 03:10

David Hempy


The documentation has been updated:

Returns the number of rows affected.

https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/Relation.html#method-i-update_all

like image 22
Patrick Avatar answered Oct 22 '22 03:10

Patrick