Skip to content

Commit 0fc8d88

Browse files
committed
Merge pull request rails#11694 from Empact/association-bind-values-not-updated-on-save
Fix that a collection proxy could be cached before the save of the owner, resulting in an invalid proxy lacking the owner’s id Conflicts: activerecord/CHANGELOG.md Conflicts: activerecord/CHANGELOG.md activerecord/lib/active_record/associations/collection_association.rb activerecord/test/cases/associations/has_many_associations_test.rb
1 parent 820e294 commit 0fc8d88

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
* Cache `CollectionAssociation#reader` proxies separately before and after
2+
the owner has been saved so that the proxy is not cached without the
3+
owner's id.
4+
5+
*Ben Woosley*
6+
7+
18
## Rails 4.0.10 (September 11, 2014) ##
29

310
* Fixed a regression where whitespaces were stripped from DISTINCT queries in

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,13 @@ def reader(force_reload = false)
3434
reload
3535
end
3636

37-
@proxy ||= CollectionProxy.new(klass, self)
37+
if owner.new_record?
38+
# Cache the proxy separately before the owner has an id
39+
# or else a post-save proxy will still lack the id
40+
@new_record_proxy ||= CollectionProxy.new(klass, self)
41+
else
42+
@proxy ||= CollectionProxy.new(klass, self)
43+
end
3844
end
3945

4046
# Implements the writer method, e.g. foo.items= for Foo.has_many :items

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,13 @@ def test_counting_using_finder_sql
411411
assert_equal 2, Firm.find(4).clients_using_sql.count
412412
end
413413

414+
def test_update_all_on_association_accessed_before_save
415+
firm = Firm.new(name: 'Firm')
416+
firm.clients << Client.first
417+
firm.save!
418+
assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!')
419+
end
420+
414421
def test_belongs_to_sanity
415422
c = Client.new
416423
assert_nil c.firm

0 commit comments

Comments
 (0)