Skip to content

Commit

Permalink
Merge pull request #48552 from gmcgibbon/fix_cpk_hmt
Browse files Browse the repository at this point in the history
Add support for unpersisted CPK has_one/has_many through associations
  • Loading branch information
gmcgibbon committed Jun 23, 2023
2 parents ba9c2e5 + 699a372 commit 1ba823d
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 2 deletions.
Expand Up @@ -113,7 +113,7 @@ def remove_records(existing_records, records, method)
end

def target_reflection_has_associated_record?
!(through_reflection.belongs_to? && owner[through_reflection.foreign_key].blank?)
!(through_reflection.belongs_to? && Array(through_reflection.foreign_key).all? { |foreign_key_column| owner[foreign_key_column].blank? })
end

def update_through_counter?(method)
Expand Down
Expand Up @@ -86,7 +86,9 @@ def stale_state
end

def foreign_key_present?
through_reflection.belongs_to? && !owner[through_reflection.foreign_key].nil?
through_reflection.belongs_to? && Array(through_reflection.foreign_key).all? do |foreign_key_column|
!owner[foreign_key_column].nil?
end
end

def ensure_mutable
Expand Down
Expand Up @@ -1631,6 +1631,14 @@ def test_tags_has_manu_posts_through_association_with_composite_query_constraint
assert_equal(expected_blog_post_ids.sort, blog_post_ids.sort)
end

def test_loading_cpk_association_with_unpersisted_owner
order = Cpk::Order.create!(shop_id: 1)
book = Cpk::BookWithOrderAgreements.new(number: 2, author_id: 1, order: order)
order_agreement = Cpk::OrderAgreement.create!(order: order)

assert_equal([order_agreement], book.order_agreements.to_a)
end

private
def make_model(name)
Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } }
Expand Down
Expand Up @@ -22,6 +22,7 @@
require "models/carrier"
require "models/shop_account"
require "models/customer_carrier"
require "models/cpk"

class HasOneThroughAssociationsTest < ActiveRecord::TestCase
fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
Expand Down Expand Up @@ -445,4 +446,12 @@ def test_has_one_through_do_not_cache_association_reader_if_the_though_method_ha
ensure
CustomerCarrier.current_customer = nil
end

def test_loading_cpk_association_with_unpersisted_owner
order = Cpk::Order.create!(shop_id: 1)
book = Cpk::BookWithOrderAgreements.new(number: 2, author_id: 1, order: order)
order_agreement = Cpk::OrderAgreement.create!(order: order)

assert_equal(order_agreement, book.order_agreement)
end
end
5 changes: 5 additions & 0 deletions activerecord/test/models/cpk/book.rb
Expand Up @@ -20,4 +20,9 @@ class BrokenBook < Book
class NullifiedBook < Book
has_one :chapter, query_constraints: [:author_id, :book_number], dependent: :nullify
end

class BookWithOrderAgreements < Book
has_many :order_agreements, through: :order
has_one :order_agreement, through: :order, source: :order_agreements
end
end

0 comments on commit 1ba823d

Please sign in to comment.