rails/rails — pull request #14849 by byroot (2014-04-23 17:01:06+00:00)
Title: Stop incrementing counter caches on association assignation

Followup of #14765 and #14735
Similar in some ways to #9236
Fixes #13304 among others

# Rationale

It's a very bad time to perform the increment because the foreign_key
change is not persisted yet and it happen outside the save transaction,
so if the update fail the increment is not rollbacked.

# Limitation

I can't make `BelongsToAssociationsTest#test_custom_counter_cache` work, because [`Reply`](https://github.com/rails/rails/blob/650585da8ac15742b64965c338110e8e859a3b5e/activerecord/test/models/reply.rb#L4-L5) belongs to `Topic` twice, so ActiveRecord think it's 2 different counters.

I'm not sure what to do with that. I think it just don't make any sense. Maybe we could prevent targeting the same counter from two associations.

# Further work

[The same issue lies in `has_many` association](https://github.com/rails/rails/blob/650585da8ac15742b64965c338110e8e859a3b5e/activerecord/test/cases/associations/has_many_associations_test.rb#L789-L795) the counters are decremented outside any transaction beside no record have been actually deleted. I'll see what I can do about that in a further PR if you don't mind.

@tenderlove @arthurnn @rafaelfranca thoughts?

/cc @jasl