From 74871961eccdb455f18e8ef66716041f2f828ba8 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Wed, 28 Jan 2009 19:20:50 +0000 Subject: =?UTF-8?q?Add=20array=20id=20support=20to=20Model.update=5Fcounte?= =?UTF-8?q?rs.=20[#1254=20state:resolved]=20[Carlos=20J=C3=BAnior]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- activerecord/lib/active_record/base.rb | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 8db3909d9a..479296ebae 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -927,7 +927,7 @@ module ActiveRecord #:nodoc: # # ==== Parameters # - # * +id+ - The id of the object you wish to update a counter on. + # * +id+ - The id of the object you wish to update a counter on or an Array of ids. # * +counters+ - An Array of Hashes containing the names of the fields # to update as keys and the amount to update the field by as values. # @@ -941,12 +941,27 @@ module ActiveRecord #:nodoc: # # SET comment_count = comment_count - 1, # # action_count = action_count + 1 # # WHERE id = 5 + # + # # For the Posts with id of 10 and 15, increment the comment_count by 1 + # Post.update_counters [10, 15], :comment_count => 1 + # # Executes the following SQL: + # # UPDATE posts + # # SET comment_count = comment_count + 1, + # # WHERE id IN (10, 15) def update_counters(id, counters) updates = counters.inject([]) { |list, (counter_name, increment)| sign = increment < 0 ? "-" : "+" list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}" }.join(", ") - update_all(updates, "#{connection.quote_column_name(primary_key)} = #{quote_value(id)}") + + if id.is_a?(Array) + ids_list = id.map {|i| quote_value(i)}.join(', ') + condition = "IN (#{ids_list})" + else + condition = "= #{quote_value(id)}" + end + + update_all(updates, "#{connection.quote_column_name(primary_key)} #{condition}") end # Increment a number field by one, usually representing a count. -- cgit v1.2.3