Skip to content

Commit 8e7627a

Browse files
authored
Merge pull request rails#53961 from byroot/increment-raise-new-record
Handle new records in `#increment!`
2 parents bec587e + e696534 commit 8e7627a

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

activerecord/lib/active_record/persistence.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,8 +641,15 @@ def increment(attribute, by = 1)
641641
# This means that any other modified attributes will still be dirty.
642642
# Validations and callbacks are skipped. Supports the +touch+ option from
643643
# +update_counters+, see that for more.
644+
#
645+
# This method raises an ActiveRecord::ActiveRecordError when called on new
646+
# objects, or when at least one of the attributes is marked as readonly.
647+
#
644648
# Returns +self+.
645649
def increment!(attribute, by = 1, touch: nil)
650+
raise ActiveRecordError, "cannot update a new record" if new_record?
651+
raise ActiveRecordError, "cannot update a destroyed record" if destroyed?
652+
646653
increment(attribute, by)
647654
change = public_send(attribute) - (public_send(:"#{attribute}_in_database") || 0)
648655
self.class.update_counters(id, attribute => change, touch: touch)

activerecord/test/cases/persistence_test.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,27 @@ def test_increment_with_no_arg
344344
assert_raises(ArgumentError) { topic.increment! }
345345
end
346346

347+
def test_increment_new_record
348+
topic = Topic.new
349+
350+
assert_no_queries do
351+
assert_raises ActiveRecord::ActiveRecordError do
352+
topic.increment!(:replies_count)
353+
end
354+
end
355+
end
356+
357+
def test_increment_destroyed_record
358+
topic = topics(:first)
359+
topic.destroy
360+
361+
assert_no_queries do
362+
assert_raises ActiveRecord::ActiveRecordError do
363+
topic.increment!(:replies_count)
364+
end
365+
end
366+
end
367+
347368
def test_destroy_many
348369
clients = Client.find([2, 3])
349370

0 commit comments

Comments
 (0)