Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #10806: add_quantity_option_to_increment_counter_and_decrement_counter_for_consistency_with_absolute.diff

File add_quantity_option_to_increment_counter_and_decrement_counter_for_consistency_with_absolute.diff, 2.2 kB (added by sur, 9 months ago)

making the 'by' value absolute for ensuring the increment and decrement

  • test/base_test.rb

    old new  
    559559 
    560560    Topic.increment_counter("replies_count", 1) 
    561561    assert_equal 3, Topic.find(1).replies_count 
     562     
     563    Topic.increment_counter("replies_count", 1, 2) 
     564    assert_equal 5, Topic.find(1).replies_count 
    562565  end 
    563566   
    564567  def test_decrement_counter 
     
    567570 
    568571    Topic.decrement_counter("replies_count", 2) 
    569572    assert_equal -2, Topic.find(2).replies_count 
     573 
     574    Topic.decrement_counter("replies_count", 2, 2) 
     575    assert_equal -4, Topic.find(2).replies_count 
    570576  end 
    571577 
    572578  def test_update_all 
  • lib/active_record/base.rb

    old new  
    781781      # 
    782782      # +counter_name+  The name of the field that should be incremented 
    783783      # +id+            The id of the object that should be incremented 
     784      # +by+            The amount by which to increment the column value (default is 1) 
    784785      # 
    785786      # ==== Examples 
    786787      # 
    787788      #   # Increment the post_count column for the record with an id of 5 
    788789      #   DiscussionBoard.increment_counter(:post_count, 5) 
    789       def increment_counter(counter_name, id
    790         update_counters(id, counter_name => 1
     790      def increment_counter(counter_name, id, by = 1
     791        update_counters(id, counter_name => by.to_i.abs
    791792      end 
    792793 
    793794      # Decrement a number field by one, usually representing a count. 
     
    798799      # 
    799800      # +counter_name+  The name of the field that should be decremented 
    800801      # +id+            The id of the object that should be decremented 
     802      # +by+            The amount by which to decrement the column value (default is 1) 
    801803      # 
    802804      # ==== Examples 
    803805      # 
    804806      #   # Decrement the post_count column for the record with an id of 5 
    805807      #   DiscussionBoard.decrement_counter(:post_count, 5) 
    806       def decrement_counter(counter_name, id
    807         update_counters(id, counter_name => -1
     808      def decrement_counter(counter_name, id, by = 1
     809        update_counters(id, counter_name => -(by.to_i.abs)
    808810      end 
    809811 
    810812