Skip to content

Commit

Permalink
Merge pull request #41370 from kamipo/serialized_attribute_on_alias_a…
Browse files Browse the repository at this point in the history
…ttribute

Allow `serialize` attribute on `alias_attribute`
  • Loading branch information
rafaelfranca committed Feb 8, 2021
2 parents d9b286b + 86fdb54 commit 8db3fef
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
2 changes: 2 additions & 0 deletions activerecord/lib/active_record/attributes.rb
Expand Up @@ -207,6 +207,8 @@ module ClassMethods
# 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
Expand Down
6 changes: 2 additions & 4 deletions activerecord/lib/active_record/enum.rb
Expand Up @@ -186,11 +186,9 @@ def _enum(name, values, prefix: nil, suffix: nil, scopes: true, **options)
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 = []
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/serialized_attribute_test.rb
Expand Up @@ -41,6 +41,21 @@ def test_serialized_attribute
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
Expand Down

0 comments on commit 8db3fef

Please sign in to comment.