From 86fdb54da1c2dd83f8d7c13c9fe6bae0ae13a419 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Mon, 8 Feb 2021 20:47:19 +0900 Subject: [PATCH] Allow `serialize` attribute on `alias_attribute` Related to #25998. --- activerecord/lib/active_record/attributes.rb | 2 ++ activerecord/lib/active_record/enum.rb | 6 ++---- .../test/cases/serialized_attribute_test.rb | 15 +++++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index fa075d1cdf..7ab9a672e8 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -207,6 +207,8 @@ module ActiveRecord # methods in ActiveModel::Type::Value for more details. def attribute(name, cast_type = nil, default: NO_DEFAULT_PROVIDED, **options) name = name.to_s + name = attribute_aliases[name] || name + reload_schema_from_cache case cast_type diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index 18996e3f15..22c662a7e2 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -186,11 +186,9 @@ module ActiveRecord detect_enum_conflict!(name, name) detect_enum_conflict!(name, "#{name}=") - attr = attribute_alias?(name) ? attribute_alias(name) : name - - attribute(attr, **options) do |subtype| + attribute(name, **options) do |subtype| subtype = subtype.subtype if EnumType === subtype - EnumType.new(attr, enum_values, subtype) + EnumType.new(name, enum_values, subtype) end value_method_names = [] diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index a750e572ec..375ab5a6a5 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -41,6 +41,21 @@ class SerializedAttributeTest < ActiveRecord::TestCase assert_equal(myobj, topic.content) end + def test_serialized_attribute_on_alias_attribute + klass = Class.new(ActiveRecord::Base) do + self.table_name = Topic.table_name + alias_attribute :object, :content + serialize :object, MyObject + end + + myobj = MyObject.new("value1", "value2") + topic = klass.create!(object: myobj) + assert_equal(myobj, topic.object) + + topic.reload + assert_equal(myobj, topic.object) + end + def test_serialized_attribute_with_default klass = Class.new(ActiveRecord::Base) do self.table_name = Topic.table_name