Skip to content

Commit 13b495b

Browse files
committed
Add better TypeError when assigning CPK
Raises a more readable error when assigning a singular ID to a model with a composite primary key.
1 parent 6be41ad commit 13b495b

File tree

2 files changed

+4
-1
lines changed

2 files changed

+4
-1
lines changed

activerecord/lib/active_record/attribute_methods/primary_key.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ def primary_key_values_present? # :nodoc:
3131
# Sets the primary key column's value.
3232
def id=(value)
3333
if self.class.composite_primary_key?
34+
raise TypeError, "Expected value matching #{self.class.primary_key.inspect}, got #{value.inspect}." unless value.is_a?(Enumerable)
3435
@primary_key.zip(value) { |attr, value| _write_attribute(attr, value) }
3536
else
3637
_write_attribute(@primary_key, value)

activerecord/test/cases/primary_keys_test.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,9 +426,11 @@ def test_assigning_a_composite_primary_key
426426
def test_assigning_a_non_array_value_to_model_with_composite_primary_key_raises
427427
book = Cpk::Book.new
428428

429-
assert_raises(TypeError) do
429+
error = assert_raises(TypeError) do
430430
book.id = 1
431431
end
432+
433+
assert_equal("Expected value matching [\"author_id\", \"number\"], got 1.", error.message)
432434
end
433435

434436
def test_id_was_composite

0 commit comments

Comments
 (0)