Skip to content

Commit

Permalink
Merge pull request rails#47872 from Shopify/dup-for-cpk-ar-models
Browse files Browse the repository at this point in the history
Reset composite primary key in `#dup`
  • Loading branch information
eileencodes authored Apr 5, 2023
2 parents f014802 + 851fb27 commit 47d0eac
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
6 changes: 5 additions & 1 deletion activerecord/lib/active_record/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,11 @@ def init_with_attributes(attributes, new_record = false) # :nodoc:
##
def initialize_dup(other) # :nodoc:
@attributes = @attributes.deep_dup
@attributes.reset(@primary_key)
if self.class.composite_primary_key?
@primary_key.each { |key| @attributes.reset(key) }
else
@attributes.reset(@primary_key)
end

_run_initialize_callbacks

Expand Down
14 changes: 13 additions & 1 deletion activerecord/test/cases/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
require "models/bulb"
require "models/pet"
require "models/owner"
require "models/cpk/book"
require "concurrent/atomic/count_down_latch"
require "active_support/core_ext/enumerable"
require "active_support/core_ext/kernel/reporting"
Expand Down Expand Up @@ -101,7 +102,9 @@ def setup
end

class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, "warehouse-things", :authors, :author_addresses, :categorizations, :categories, :posts
fixtures :topics, :companies, :developers, :projects, :computers, :accounts,
:minimalistics, "warehouse-things", :authors, :author_addresses, :categorizations, :categories,
:posts, :cpk_books

def test_generated_association_methods_module_name
mod = Post.send(:generated_association_methods)
Expand Down Expand Up @@ -1002,6 +1005,15 @@ def test_dup
assert_equal("c", duped_topic.title)
end

def test_dup_for_a_composite_primary_key_model
book = cpk_books(:cpk_great_author_first_book)
new_book = book.dup

assert_equal "The first book", new_book.title
assert_nil new_book.author_id
assert_nil new_book.number
end

DeveloperSalary = Struct.new(:amount)
def test_dup_with_aggregate_of_same_name_as_attribute
developer_with_aggregate = Class.new(ActiveRecord::Base) do
Expand Down

0 comments on commit 47d0eac

Please sign in to comment.