update_attribute updates too much

Hi all. Maybe somebody can explain that to me:

def create   @orders = Order.find(:all, :conditions => ["products.member_id = ?", current_login.member.id])   # new payment   @payment = Payment.new   @payment.member = current_login.member   @payment.status = Payment::STATUS_NEW   @payment.save

  sum = 0.00   @orders.each do |order|     order.payment = @payment     order.save     sum += 2950   end logger.info "COUNT A: #{@payment.orders_count}"       @payment.update_attribute(:total, sum) @payment.reload logger.info "COUNT B: #{@payment.orders_count}"

works fine but for one point: The counter cache is 0 after that.

Reason is this.

While the line

order.payment = @payment

generates the necessary code to update the counter_cache (twice):

UPDATE payments SET `orders_count` = `orders_count` + 1 WHERE (`id` = 1017343603)

the update_attribute line updates more than necessary:

UPDATE `payments` SET `created_at` = '2008-06-03 18:42:03', `member_id` = 762526581, `status` = 1, `orders_count` = 0, `total` = 5900.0, `updated_at` = '2008-06-03 18:42:03' WHERE `id` = 1017343603

Why is it updating not only the total and updated_at, but in addition a whole set of different columns, that where not even changed since the @payment.save?

Am I doing something terribly wrong? I could handle this for the specific problem, but I see a lot of possible side effects here and would at least want to understand, what's the reason for Rails to behave that way...

the update_attribute line updates more than necessary:

UPDATE `payments` SET `created_at` = '2008-06-03 18:42:03',
`member_id` = 762526581, `status` = 1, `orders_count` = 0, `total` = 5900.0, `updated_at` = '2008-06-03 18:42:03' WHERE `id` = 1017343603

Why is it updating not only the total and updated_at, but in
addition a whole set of different columns, that where not even changed since the @payment.save?

Just the way rails is. In 2.1 you can turn on partial_updates

Fred

Just the way rails is. In 2.1 you can turn on partial_updates

Fred

Thanks Fred, so at least I know that I have to be a bit more careful with update_attributes. I will give partial_updates a try

thorsten