brainspec / enumerize

Enumerated attributes with I18n and ActiveRecord/Mongoid support
MIT License
1.73k stars 190 forks source link

`#becomes` fails when only an STI subclass includes `Enumerize`, and not its base class #426

Closed lorint closed 6 months ago

lorint commented 1 year ago

Given an ActiveRecord class Animal which has a subclass Cat:

class Animal < ApplicationRecord
end

class Cat < Animal
  include Enumerize
end

When a form for Animal is built in this kind of way so that it will post back to AnimalsController (instead of CatsController):

<%= form_for(@cat.becomes(Animal)) do |f| %>
  ...
<% end %>

Then when the overridden version of #becomes from Enumerize is called, this error surfaces:

NoMethodError - undefined method `enumerized_attributes' for Animal:Class:

In order to remedy this issue, it is possible to add a line to reset klass when necessary before calling #enumerized_attributes:

# lib/enumerize/activerecord.rb:
...
    def becomes(klass)
      became = super
      klass = self.class unless klass.respond_to?(:enumerized_attributes) # <-- Add this line
      klass.enumerized_attributes.each do |attr|
...

Will open a PR to address this issue.