mirror of https://github.com/rails/rails
Make has_many through singular associations build CPK records
Adds support for building records in has_many through has_one composite primary key associations. Also updates query constraints on associations affected by rails/rails#48564.
This commit is contained in:
parent
d1a79da376
commit
3fc9ade23b
|
@ -118,7 +118,9 @@ module ActiveRecord
|
|||
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
|
||||
|
|
|
@ -1650,6 +1650,14 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
|
|||
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 } }
|
||||
|
|
|
@ -7,7 +7,7 @@ module Cpk
|
|||
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
|
||||
|
@ -18,7 +18,7 @@ module Cpk
|
|||
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
|
||||
|
|
|
@ -7,6 +7,6 @@ module Cpk
|
|||
# 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
|
||||
|
|
|
@ -24,4 +24,8 @@ module Cpk
|
|||
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
|
||||
|
|
Loading…
Reference in New Issue