Skip to content

Commit b0af8c9

Browse files
committed
Make sure attribute_aliases is consistent
Before this change `attribute_aliases` would be empty if the model class didn't define any attribute yet.
1 parent f39522b commit b0af8c9

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

activerecord/lib/active_record/attribute_methods.rb

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,6 @@ def define_attribute_methods # :nodoc:
120120
unless abstract_class?
121121
load_schema
122122
super(attribute_names)
123-
if _has_attribute?("id")
124-
alias_attribute(:id_value, :id)
125-
end
126123
end
127124

128125
ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |code_generator|

activerecord/lib/active_record/model_schema.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,7 @@ def load_schema!
583583
columns_hash = connection.schema_cache.columns_hash(table_name)
584584
columns_hash = columns_hash.except(*ignored_columns) unless ignored_columns.empty?
585585
@columns_hash = columns_hash.freeze
586+
alias_attribute :id_value, :id if @columns_hash.key?("id")
586587
end
587588

588589
# Guesses the table name, but does not decorate it with prefix and suffix information.

activerecord/test/cases/attribute_methods_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,15 @@ def setup
3232
ActiveRecord::Base.send(:attribute_method_patterns).concat(@old_matchers)
3333
end
3434

35+
test "#id_value alias is defined if id column exist" do
36+
new_topic_model = Class.new(ActiveRecord::Base) do
37+
self.table_name = "topics"
38+
end
39+
40+
assert_includes new_topic_model.attribute_names, "id"
41+
assert_includes new_topic_model.attribute_aliases, "id_value"
42+
end
43+
3544
test "aliasing `id` attribute allows reading the column value" do
3645
topic = Topic.create(id: 123_456, title: "title").becomes(TitlePrimaryKeyTopic)
3746

0 commit comments

Comments
 (0)