Skip to content

Commit e90b11e

Browse files
Use alias_attribute to provide #id_value alias for #id
This allows access to the raw id column value on records for which an id column exists but is not the primary key. This is common amongst models with composite primary keys.
1 parent 81fa913 commit e90b11e

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

activerecord/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* Add `ActiveRecord::Base#id_value` alias to access the raw value of a record's id column.
2+
3+
This alias is only provided for models that declare an `:id` column.
4+
5+
*Adrianna Chang*
6+
17
* Fix previous change tracking for `ActiveRecord::Store` when using a column with JSON structured database type
28

39
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

activerecord/lib/active_record/model_schema.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,7 @@ def load_schema!
618618
default: column.default,
619619
user_provided_default: false
620620
)
621+
alias_attribute :id_value, :id if name == "id"
621622
end
622623

623624
super

activerecord/test/cases/attribute_methods_test.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,26 @@ def setup
4444
assert_equal(123_456, order.id_value)
4545
end
4646

47+
test "#id_value alias returns the value in the id column, when id column exists" do
48+
topic = Topic.new
49+
assert_nil topic.id_value
50+
51+
topic = Topic.find(1)
52+
assert_equal 1, topic.id_value
53+
end
54+
55+
test "#id_value alias is not defined if id column doesn't exist" do
56+
keyboard = Keyboard.create!
57+
58+
assert_empty keyboard.attribute_aliases
59+
end
60+
61+
test "#id_value alias returns id column only for composite primary key models" do
62+
order = ::Cpk::Order.create(id: [1, 2])
63+
64+
assert_equal 2, order.id_value
65+
end
66+
4767
test "attribute_for_inspect with a string" do
4868
t = topics(:first)
4969
t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"

0 commit comments

Comments
 (0)