Skip to content

Commit 3bdee53

Browse files
authored
Merge pull request rails#53658 from fatkodima/reset-cpk-when-configuring-pk
Properly reset composite primary key configuration when setting a primary key
2 parents 4df235f + 169ff5d commit 3bdee53

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

activerecord/lib/active_record/attribute_methods/primary_key.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,13 @@ def get_primary_key(base_name) # :nodoc:
129129
# Project.primary_key # => "foo_id"
130130
def primary_key=(value)
131131
@primary_key = if value.is_a?(Array)
132-
@composite_primary_key = true
133132
include CompositePrimaryKey
134133
@primary_key = value.map { |v| -v.to_s }.freeze
135134
elsif value
136135
-value.to_s
137136
end
137+
138+
@composite_primary_key = value.is_a?(Array)
138139
@attributes_builder = nil
139140
end
140141

activerecord/test/cases/primary_keys_test.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,17 @@ def test_assign_id_raises_error_if_primary_key_doesnt_exist
256256
assert_raises(ActiveModel::MissingAttributeError) { dashboard.id = "1" }
257257
end
258258

259+
def test_reconfiguring_primary_key_resets_composite_primary_key
260+
klass = Class.new(ActiveRecord::Base) do
261+
self.table_name = "cpk_books"
262+
end
263+
264+
assert_predicate klass, :composite_primary_key?
265+
266+
klass.primary_key = :id
267+
assert_not_predicate klass, :composite_primary_key?
268+
end
269+
259270
def composite_primary_key_is_false_for_a_non_cpk_model
260271
assert_not_predicate Dashboard, :composite_primary_key?
261272
end

0 commit comments

Comments
 (0)