Skip to content

Commit 007a609

Browse files
authored
Merge pull request rails#51785 from fatkodima/touch_all-in-batches
Support `touch_all` in batches
2 parents e97db3b + e057037 commit 007a609

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
* Support `touch_all` in batches.
2+
3+
```ruby
4+
Post.in_batches.touch_all
5+
```
6+
7+
*fatkodima*
8+
19
* Add support for `:if_not_exists` and `:force` options to `create_schema`
210

311
*fatkodima*

activerecord/lib/active_record/relation/batches/batch_enumerator.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,17 @@ def update_all(updates)
7777
end
7878
end
7979

80+
# Touches records in batches. Returns the total number of rows affected.
81+
#
82+
# Person.in_batches.touch_all
83+
#
84+
# See Relation#touch_all for details of how each batch is touched.
85+
def touch_all(...)
86+
sum do |relation|
87+
relation.touch_all(...)
88+
end
89+
end
90+
8091
# Destroys records in batches.
8192
#
8293
# Person.where("age < 10").in_batches.destroy_all

activerecord/test/cases/batches_test.rb

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
require "models/comment"
55
require "models/post"
66
require "models/subscriber"
7+
require "models/developer"
78
require "models/cpk"
89

910
class EachTest < ActiveRecord::TestCase
10-
fixtures :posts, :subscribers, :cpk_orders
11+
fixtures :posts, :subscribers, :developers, :cpk_orders
1112

1213
def setup
1314
@posts = Post.order("id asc")
@@ -384,6 +385,22 @@ def test_in_batches_update_all_returns_zero_when_no_batches
384385
assert_equal 0, Post.where("1=0").in_batches(of: 2).update_all(title: "updated-title")
385386
end
386387

388+
def test_in_batches_touch_all_affect_all_records
389+
time = Time.new(2000, 1, 1, 0, 0, 0)
390+
assert_queries_count(6 + 6) do # 6 selects, 6 updates
391+
Developer.in_batches(of: 2).touch_all(time: time)
392+
end
393+
assert_equal Developer.all.pluck(:updated_at), [time] * Developer.count
394+
end
395+
396+
def test_in_batches_touch_all_returns_rows_affected
397+
assert_equal 11, Developer.in_batches(of: 2).touch_all
398+
end
399+
400+
def test_in_batches_touch_all_returns_zero_when_no_batches
401+
assert_equal 0, Developer.where("1=0").in_batches(of: 2).touch_all
402+
end
403+
387404
def test_in_batches_delete_all_should_not_delete_records_in_other_batches
388405
not_deleted_count = Post.where("id <= 2").count
389406
Post.where("id > 2").in_batches(of: 2).delete_all

0 commit comments

Comments
 (0)