Skip to content

Commit ac6217d

Browse files
committed
Ensure association's foreign_key: and query_constraints: options behave the same
1 parent d37c533 commit ac6217d

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

activerecord/lib/active_record/reflection.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,10 @@ def initialize(name, scope, options, active_record)
516516
@foreign_key = nil
517517
@association_foreign_key = nil
518518
@association_primary_key = nil
519+
# If the foreign key is an array, set query constraints options and don't use the foreign key
520+
if options[:foreign_key].is_a?(Array)
521+
options[:query_constraints] = options.delete(:foreign_key)
522+
end
519523

520524
ensure_option_not_given_as_class!(:class_name)
521525
end

activerecord/test/cases/associations/inverse_associations_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,20 @@ def test_polymorphic_has_one_should_find_inverse_automatically
227227

228228
assert_predicate human_reflection, :has_inverse?
229229
end
230+
231+
def test_has_many_inverse_of_derived_automatically_despite_of_composite_foreign_key
232+
car_review_reflection = Cpk::Car.reflect_on_association(:car_reviews)
233+
234+
assert_predicate car_review_reflection, :has_inverse?
235+
assert_equal Cpk::CarReview.reflect_on_association(:car), car_review_reflection.inverse_of
236+
end
237+
238+
def test_belongs_to_inverse_of_derived_automatically_despite_of_composite_foreign_key
239+
car_reflection = Cpk::CarReview.reflect_on_association(:car)
240+
241+
assert_predicate car_reflection, :has_inverse?
242+
assert_equal Cpk::Car.reflect_on_association(:car_reviews), car_reflection.inverse_of
243+
end
230244
end
231245

232246
class InverseAssociationTests < ActiveRecord::TestCase

activerecord/test/models/cpk/car.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,7 @@
33
module Cpk
44
class Car < ActiveRecord::Base
55
self.table_name = :cpk_cars
6+
7+
has_many :car_reviews, foreign_key: [:car_make, :car_model]
68
end
79
end

0 commit comments

Comments
 (0)