Skip to content

Commit ab27c24

Browse files
authored
Merge pull request rails#50701 from rails/rm-load-schema
Make sure attribute_aliases is consistent
2 parents 2335328 + f60b1d5 commit ab27c24

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-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/attribute_methods/primary_key.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ def inherited(base)
152152
@attributes_builder = nil
153153
end
154154
end
155+
156+
def load_schema! # :nodoc:
157+
super
158+
alias_attribute :id_value, :id if @columns_hash.key?("id")
159+
end
155160
end
156161
end
157162
end

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)