Skip to content

Commit

Permalink
Add better TypeError when assigning CPK
Browse files Browse the repository at this point in the history
Raises a more readable error when assigning a singular ID to a
model with a composite primary key.
  • Loading branch information
gmcgibbon committed Jun 9, 2023
1 parent 6be41ad commit 13b495b
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def primary_key_values_present? # :nodoc:
# Sets the primary key column's value.
def id=(value)
if self.class.composite_primary_key?
raise TypeError, "Expected value matching #{self.class.primary_key.inspect}, got #{value.inspect}." unless value.is_a?(Enumerable)
@primary_key.zip(value) { |attr, value| _write_attribute(attr, value) }
else
_write_attribute(@primary_key, value)
Expand Down
4 changes: 3 additions & 1 deletion activerecord/test/cases/primary_keys_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,11 @@ def test_assigning_a_composite_primary_key
def test_assigning_a_non_array_value_to_model_with_composite_primary_key_raises
book = Cpk::Book.new

assert_raises(TypeError) do
error = assert_raises(TypeError) do
book.id = 1
end

assert_equal("Expected value matching [\"author_id\", \"number\"], got 1.", error.message)
end

def test_id_was_composite
Expand Down

0 comments on commit 13b495b

Please sign in to comment.