Skip to content

Commit 10e8624

Browse files
committed
Accept composite primary key in id=
1 parent d53dc86 commit 10e8624

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

activerecord/lib/active_record/attribute_methods/primary_key.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@ def id
2323

2424
# Sets the primary key column's value.
2525
def id=(value)
26-
_write_attribute(@primary_key, value)
26+
if self.class.composite_primary_key?
27+
@primary_key.zip(value) { |attr, value| _write_attribute(attr, value) }
28+
else
29+
_write_attribute(@primary_key, value)
30+
end
2731
end
2832

2933
# Queries the primary key column's value.

activerecord/test/cases/primary_keys_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,22 @@ def test_composite_primary_key_out_of_order
373373
assert_equal ["code", "region"], @connection.primary_keys("barcodes_reverse")
374374
end
375375

376+
def test_assigning_a_composite_primary_key
377+
book = Cpk::Book.new
378+
book.id = [1, 2]
379+
book.save!
380+
381+
assert_equal [1, 2], book.id
382+
end
383+
384+
def test_assigning_a_non_array_value_to_model_with_composite_primary_key_raises
385+
book = Cpk::Book.new
386+
387+
assert_raises(TypeError) do
388+
book.id = 1
389+
end
390+
end
391+
376392
def test_primary_key_issues_warning
377393
model = Class.new(ActiveRecord::Base) do
378394
def self.table_name

0 commit comments

Comments
 (0)