Skip to content

Commit

Permalink
Merge pull request #48930 from adrianna-chang-shopify/ac-id-value
Browse files Browse the repository at this point in the history
Use `alias_attribute` to provide `id_value` alias for `id` attribute
  • Loading branch information
rafaelfranca committed Aug 21, 2023
2 parents 6beb348 + e90b11e commit ccee593
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,9 @@
* Add `ActiveRecord::Base#id_value` alias to access the raw value of a record's id column.

This alias is only provided for models that declare an `:id` column.

*Adrianna Chang*

* Fix previous change tracking for `ActiveRecord::Store` when using a column with JSON structured database type

Before, the methods to access the changes made during the last save `#saved_change_to_key?`, `#saved_change_to_key`, and `#key_before_last_save` did not work if the store was defined as a `store_accessor` on a column with a JSON structured database type
Expand Down
1 change: 1 addition & 0 deletions activerecord/lib/active_record/model_schema.rb
Expand Up @@ -618,6 +618,7 @@ def load_schema!
default: column.default,
user_provided_default: false
)
alias_attribute :id_value, :id if name == "id"
end

super
Expand Down
20 changes: 20 additions & 0 deletions activerecord/test/cases/attribute_methods_test.rb
Expand Up @@ -44,6 +44,26 @@ def setup
assert_equal(123_456, order.id_value)
end

test "#id_value alias returns the value in the id column, when id column exists" do
topic = Topic.new
assert_nil topic.id_value

topic = Topic.find(1)
assert_equal 1, topic.id_value
end

test "#id_value alias is not defined if id column doesn't exist" do
keyboard = Keyboard.create!

assert_empty keyboard.attribute_aliases
end

test "#id_value alias returns id column only for composite primary key models" do
order = ::Cpk::Order.create(id: [1, 2])

assert_equal 2, order.id_value
end

test "attribute_for_inspect with a string" do
t = topics(:first)
t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"
Expand Down

0 comments on commit ccee593

Please sign in to comment.