Skip to content

Commit

Permalink
Merge pull request #48998 from Shopify/to_key-supports-composite-prim…
Browse files Browse the repository at this point in the history
…ary-key

Support composite identifiers in `to_key`
  • Loading branch information
rafaelfranca committed Aug 22, 2023
2 parents 3338621 + 8a5cf4c commit ed5af00
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 2 deletions.
10 changes: 10 additions & 0 deletions actionview/test/lib/controller/fake_models.rb
Expand Up @@ -217,3 +217,13 @@ def save
@to_key = [1]
end
end

class CompositePrimaryKeyRecord
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_reader :id

def initialize(id)
@id = id
end
end
5 changes: 5 additions & 0 deletions actionview/test/template/record_identifier_test.rb
Expand Up @@ -30,6 +30,11 @@ def test_dom_id_with_saved_record
assert_equal "#{@singular}_1", dom_id(@record)
end

def test_dom_id_with_composite_primary_key_record
record = CompositePrimaryKeyRecord.new([1, 123])
assert_equal("composite_primary_key_record_1_123", dom_id(record))
end

def test_dom_id_with_prefix
@record.save
assert_equal "edit_#{@singular}_1", dom_id(@record, :edit)
Expand Down
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/conversion.rb
Expand Up @@ -58,7 +58,7 @@ def to_model
# person.to_key # => [1]
def to_key
key = respond_to?(:id) && id
key ? [key] : nil
key ? Array(key) : nil
end

# Returns a +string+ representing the object's key suitable for use in URLs,
Expand Down
4 changes: 4 additions & 0 deletions activemodel/test/cases/conversion_test.rb
Expand Up @@ -18,6 +18,10 @@ class ConversionTest < ActiveModel::TestCase
assert_equal [1], Contact.new(id: 1).to_key
end

test "to_key doesn't double-wrap composite `id`s" do
assert_equal ["abc", "xyz"], Contact.new(id: ["abc", "xyz"]).to_key
end

test "to_param default implementation returns nil for new records" do
assert_nil Contact.new.to_param
end
Expand Down
Expand Up @@ -12,7 +12,7 @@ module PrimaryKey
# available.
def to_key
key = id
[key] if key
Array(key) if key
end

# Returns the primary key column's value.
Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/primary_keys_test.rb
Expand Up @@ -29,6 +29,13 @@ def test_to_key_with_customized_primary_key
assert_equal keyboard.to_key, [keyboard.id]
end

def test_to_key_with_composite_primary_key
order = Cpk::Order.new
assert_equal [nil, nil], order.to_key
order.id = [1, 2]
assert_equal [1, 2], order.to_key
end

def test_read_attribute_with_custom_primary_key
keyboard = Keyboard.create!
assert_equal keyboard.key_number, keyboard.read_attribute(:id)
Expand Down

0 comments on commit ed5af00

Please sign in to comment.