Skip to content

Commit

Permalink
Don't register aliased attributes in attributes_types
Browse files Browse the repository at this point in the history
In rails 7.1, this was failing when trying to access the virtual
aliased attribute with: ActiveModel::MissingAttributeError.
Perhaps, we're registering it incorrectly as rails has had attribute_alias
and friends methods and supports it on it's own.

For now, we only register non-aliased attributes in attribute_types
but bring them back in virtual_attribute_names since they are already
attributes (but aliases) but still virtual.
  • Loading branch information
jrafanie committed Jan 16, 2025
1 parent 6580fc6 commit afd9619
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions lib/active_record/virtual_attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,22 @@ def virtual_attribute?(name)
)
end

def virtual_attribute_alias?(name)
return false unless respond_to?(:attribute_alias?)

attribute_alias?(name) && virtual_attributes_to_define.keys.include?(name)
end

def virtual_attribute_alias_names
return [] unless respond_to?(:attribute_alias?)

virtual_attributes_to_define.keys.select {|name| attribute_alias?(name) }
end

def virtual_attribute_names
if respond_to?(:column_names)
attribute_names - column_names
else
attribute_names
end
names = attribute_names | virtual_attribute_alias_names
names -= column_names if respond_to?(:column_names)
names
end

private
Expand All @@ -101,7 +111,7 @@ def load_schema!
end

def define_virtual_attribute(name, cast_type, uses: nil, arel: nil)
attribute_types[name] = cast_type
attribute_types[name] = cast_type unless virtual_attribute_alias?(name)
define_virtual_include(name, uses) if uses
define_virtual_arel(name, arel) if arel
end
Expand Down

0 comments on commit afd9619

Please sign in to comment.