File tree Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -641,8 +641,15 @@ def increment(attribute, by = 1)
641
641
# This means that any other modified attributes will still be dirty.
642
642
# Validations and callbacks are skipped. Supports the +touch+ option from
643
643
# +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
+ #
644
648
# Returns +self+.
645
649
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
+
646
653
increment ( attribute , by )
647
654
change = public_send ( attribute ) - ( public_send ( :"#{ attribute } _in_database" ) || 0 )
648
655
self . class . update_counters ( id , attribute => change , touch : touch )
Original file line number Diff line number Diff line change @@ -344,6 +344,27 @@ def test_increment_with_no_arg
344
344
assert_raises ( ArgumentError ) { topic . increment! }
345
345
end
346
346
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
+
347
368
def test_destroy_many
348
369
clients = Client . find ( [ 2 , 3 ] )
349
370
You can’t perform that action at this time.
0 commit comments