Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make has_many through singular associations build CPK records #48650

Merged
merged 1 commit into from Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -118,7 +118,9 @@ def build_record(attributes)
target = through_association.target

if inverse && target && !target.is_a?(Array)
attributes[inverse.foreign_key] = target.id
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

super
Expand Down
Expand Up @@ -1650,6 +1650,14 @@ def test_cpk_stale_target
assert_predicate(book.association(:order_agreements), :stale_target?)
end

def test_cpk_association_build_through_singular
order = Cpk::OrderWithSingularBookChapters.create!(id: [1, 2])
book = order.create_book!(id: [3, 4])
chapter = order.chapters.build

assert_equal(chapter.book, book)
end

private
def make_model(name)
Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } }
Expand Down
4 changes: 2 additions & 2 deletions activerecord/test/models/cpk/book.rb
Expand Up @@ -7,7 +7,7 @@ class Book < ActiveRecord::Base
belongs_to :order, autosave: true, query_constraints: [:shop_id, :order_id]
belongs_to :author, class_name: "Cpk::Author"

has_many :chapters, query_constraints: [:author_id, :book_number]
has_many :chapters, query_constraints: [:author_id, :book_id]
end

class BestSeller < Book
Expand All @@ -18,7 +18,7 @@ class BrokenBook < Book
end

class NullifiedBook < Book
has_one :chapter, query_constraints: [:author_id, :book_number], dependent: :nullify
has_one :chapter, query_constraints: [:author_id, :book_id], dependent: :nullify
end

class BookWithOrderAgreements < Book
Expand Down
2 changes: 1 addition & 1 deletion activerecord/test/models/cpk/chapter.rb
Expand Up @@ -7,6 +7,6 @@ class Chapter < ActiveRecord::Base
# to be shared between different databases
self.primary_key = [:author_id, :id]

belongs_to :book, query_constraints: [:author_id, :book_number]
belongs_to :book, query_constraints: [:author_id, :book_id]
end
end
4 changes: 4 additions & 0 deletions activerecord/test/models/cpk/order.rb
Expand Up @@ -24,4 +24,8 @@ class OrderWithPrimaryKeyAssociatedBook < Order
class OrderWithNullifiedBook < Order
has_one :book, query_constraints: [:shop_id, :order_id], dependent: :nullify
end

class OrderWithSingularBookChapters < Order
has_many :chapters, through: :book
end
end