diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index d013988ec475c..96bf5dd705df1 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -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, diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index e63fbd7ea1625..fabe8349dfeb4 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -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 diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index b986661e9b5a6..f4ab80f06889b 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -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 @@ -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.