Merge pull request #48674 from gmcgibbon/hmt_singular_fix

Fix has_one through singular building with inverse.
This commit is contained in:
Eileen M. Uchitelle 2023-07-06 09:09:28 -04:00 committed by GitHub
commit fc1886757d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 6 deletions

@ -1,3 +1,12 @@
* Fix has_one through singular building with inverse.
Allows building of records from an association with a has_one through a
singular association with inverse. For belongs_to through associations,
linking the foreign key to the primary key model isn't needed.
For has_one, we cannot build records due to the association not being mutable.
*Gannon McGibbon*
* Disable database prepared statements when query logs are enabled
Prepared Statements and Query Logs are incompatible features due to query logs making every query unique.

@ -114,12 +114,14 @@ def ensure_not_nested
end
def build_record(attributes)
inverse = source_reflection.inverse_of
target = through_association.target
if source_reflection.collection?
inverse = source_reflection.inverse_of
target = through_association.target
if inverse && target && !target.is_a?(Array)
Array(target.id).zip(Array(inverse.foreign_key)).map do |primary_key_value, foreign_key_column|
attributes[foreign_key_column] = primary_key_value
if inverse && target && !target.is_a?(Array)
Array(target.id).zip(Array(inverse.foreign_key)).map do |primary_key_value, foreign_key_column|
attributes[foreign_key_column] = primary_key_value
end
end
end

@ -100,6 +100,14 @@ def test_building_multiple_associations_builds_through_record
assert_predicate member_detail_with_two_associations.member, :new_record?
end
def test_building_works_with_has_one_through_belongs_to
new_member = Member.create!(name: "Joe")
new_member.create_current_membership!
new_club = new_member.build_club
assert_equal(new_member.club, new_club)
end
def test_creating_multiple_associations_creates_through_record
member_type = MemberType.create!
member = Member.create!

@ -8,7 +8,7 @@ class Membership < ActiveRecord::Base
class CurrentMembership < Membership
belongs_to :member
belongs_to :club
belongs_to :club, inverse_of: :membership
end
class SuperMembership < Membership