Skip to content

Commit 22a61df

Browse files
authored
Merge pull request rails#50297 from iamradioactive/handle_composite_foreign_keys
Fix stale state for composite foreign keys in belongs_to association
2 parents 405c2dd + c500ca9 commit 22a61df

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

activerecord/lib/active_record/associations/belongs_to_association.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,9 @@ def invertible_for?(record)
162162
end
163163

164164
def stale_state
165-
owner._read_attribute(reflection.foreign_key) { |n| owner.send(:missing_attribute, n, caller) }
165+
Array(reflection.foreign_key).map do |fk|
166+
owner._read_attribute(fk) { |n| owner.send(:missing_attribute, n, caller) }
167+
end
166168
end
167169
end
168170
end

activerecord/test/cases/associations/belongs_to_associations_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
require "models/node"
3232
require "models/club"
3333
require "models/cpk"
34+
require "models/sharded/blog"
35+
require "models/sharded/blog_post"
36+
require "models/sharded/comment"
3437

3538
class BelongsToAssociationsTest < ActiveRecord::TestCase
3639
fixtures :accounts, :companies, :developers, :projects, :topics,
@@ -400,6 +403,18 @@ def test_should_set_composite_foreign_key_on_association_when_key_changes_on_ass
400403
assert_equal 3, book.shop_id
401404
end
402405

406+
def test_should_reload_association_on_model_with_query_constraints_when_foreign_key_changes
407+
blog = Sharded::Blog.create!
408+
blog_post = Sharded::BlogPost.create!(blog: blog)
409+
comment = Sharded::Comment.create!(blog: blog)
410+
411+
# Load the association once
412+
comment.blog_post
413+
comment.blog_post_id = blog_post.id
414+
415+
assert_equal blog_post, comment.blog_post
416+
end
417+
403418
def test_building_the_belonging_object_with_implicit_sti_base_class
404419
account = Account.new
405420
company = account.build_firm

0 commit comments

Comments
 (0)