Skip to content

Commit

Permalink
Merge pull request #48436 from gmcgibbon/cpk_malformed_key
Browse files Browse the repository at this point in the history
Add better TypeError when assigning CPK
  • Loading branch information
eileencodes committed Jun 12, 2023
2 parents 716baea + 13b495b commit a14c5f0
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
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
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 a14c5f0

Please sign in to comment.