Skip to content

Commit

Permalink
Fix setting inverses for composite primary key associations
Browse files Browse the repository at this point in the history
Checking whether a record has a foreign key for a composite primary key
association requires us to check whether all parts of the foreign key
are present. Otherwise, the inverse association will not be set.
  • Loading branch information
adrianna-chang-shopify committed Jun 15, 2023
1 parent 01363bd commit 4e53fd0
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/associations/association.rb
Expand Up @@ -336,7 +336,8 @@ def invertible_for?(record)

# Returns true if record contains the foreign_key
def foreign_key_for?(record)
record._has_attribute?(reflection.foreign_key)
foreign_key = Array(reflection.foreign_key)
foreign_key.all? { |key| record._has_attribute?(key) }
end

# This should be implemented to return the values of the relevant key(s) on the owner,
Expand Down
Expand Up @@ -365,6 +365,17 @@ def test_building_the_belonging_object_for_composite_primary_key
assert_equal id, cpk_book.order_id
end

def test_belongs_to_with_inverse_association_for_composite_primary_key
author = Cpk::Author.new(name: "John")
book = author.books.build(number: 1, title: "The Rails Way")
order = Cpk::Order.new(book: book, status: "paid")
author.save!

_order_shop_id, order_id = order.id
assert order_id
assert_equal order_id, book.order_id
end

def test_building_the_belonging_object_with_implicit_sti_base_class
account = Account.new
company = account.build_firm
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/associations/inverse_associations_test.rb
Expand Up @@ -26,6 +26,7 @@
require "models/subscription"
require "models/book"
require "models/branch"
require "models/cpk"

class AutomaticInverseFindingTests < ActiveRecord::TestCase
fixtures :ratings, :comments, :cars, :books
Expand Down Expand Up @@ -602,6 +603,15 @@ def test_find_on_child_instances_with_ids_should_set_inverse_instances
end
end

def test_inverse_should_be_set_on_composite_primary_key_child
author = Cpk::Author.new(name: "John")
book = author.books.build(number: 1, title: "The Rails Way")
Cpk::Order.new(book: book, status: "paid")
author.save!

assert book.association(:order).loaded?
end

def test_raise_record_not_found_error_when_invalid_ids_are_passed
# delete all interest records to ensure that hard coded invalid_id(s)
# are indeed invalid.
Expand Down

0 comments on commit 4e53fd0

Please sign in to comment.