Skip to content

Commit

Permalink
Merge pull request #47565 from Shopify/fix-nullifying-association-wit…
Browse files Browse the repository at this point in the history
…h-composite-query-constraints

Fix nullifying association with composite query constraints
  • Loading branch information
eileencodes committed Mar 3, 2023
2 parents d90d389 + 2faba74 commit 8200a3d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def foreign_key_present?

def nullified_owner_attributes
Hash.new.tap do |attrs|
attrs[reflection.foreign_key] = nil
Array(reflection.foreign_key).each { |foreign_key| attrs[foreign_key] = nil }
attrs[reflection.type] = nil if reflection.type.present?
end
end
Expand Down
28 changes: 28 additions & 0 deletions activerecord/test/cases/associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,21 @@ def test_append_composite_foreign_key_has_many_association
assert_equal(blog_post.blog_id, comment.blog_id)
end

def test_nullify_composite_foreign_key_has_many_association
blog_post = sharded_blog_posts(:great_post_blog_one)
comment = sharded_comments(:great_comment_blog_post_one)

assert_not_empty(blog_post.comments)
blog_post.comments = []

comment = Sharded::Comment.find(comment.id)
assert_nil(comment.blog_post_id)
assert_nil(comment.blog_id)

assert_empty(blog_post.comments)
assert_empty(blog_post.reload.comments)
end

def test_assign_persisted_composite_foreign_key_belongs_to_association
comment = sharded_comments(:great_comment_blog_post_one)
another_blog = sharded_blogs(:sharded_blog_two)
Expand All @@ -192,6 +207,19 @@ def test_assign_persisted_composite_foreign_key_belongs_to_association
assert_equal(comment.blog_post_id, blog_post.id)
end

def test_nullify_composite_foreign_key_belongs_to_association
comment = sharded_comments(:great_comment_blog_post_one)
assert_not_nil(comment.blog_post)

comment.blog_post = nil
assert_nil(comment.blog_id)
assert_nil(comment.blog_post_id)

comment.save
assert_nil(comment.blog_post)
assert_nil(comment.reload.blog_post)
end

def test_assign_composite_foreign_key_belongs_to_association
comment = sharded_comments(:great_comment_blog_post_one)
another_blog = sharded_blogs(:sharded_blog_two)
Expand Down

0 comments on commit 8200a3d

Please sign in to comment.