enumerate_it icon indicating copy to clipboard operation
enumerate_it copied to clipboard

Translate enumeration value to associated polymorphic instance

Open gduprey opened this issue 6 years ago • 1 comments

When using polymorphic enumerations, after I assign a value to a properly setup ActiveRecord model field, I can then reference that field with a _object suffix and then access the polymorphic instance method for the currently assigned value. Using the project documentation as an example, I can write

p.relationship_status_object.saturday_night

However, if I have a enumeration value that I have not assigned to a record/model (e.g. want to filter through enumerations for a particular related value), there is no easy way to get that _object reference if in order to access that polymorphic instance method. Right now, we're hacking around this with a method like this:

def type_instance(type)
  Payroll::TaxTableType.const_get(type.titleize.gsub(' ','')).new
end

# Access via ActiveRecord model assignment
myRec.tax_type = Payroll::TaxTableType::FICA
myRec.tax_type_object.maximum_brackets

# Access without assigning value to an ActiveRecord model
x = type_instance(Payroll::TaxTableType::FICA)
x.maximum_brackets

(where the Payroll::TaxTableType is an enumeration class and maximum_brackets is a method defined for each possible Payroll::TaxTableType enumeration value via polymorphic class objects for each enumeration value).

It feels like there should be an enumeration method that, given an enumeration value (what is actually stored in such a field) can be translated into an instance of that values polymorphic class without having to first assign a value to an ActiveRecord field/attribute.

gduprey avatar Feb 18 '19 16:02 gduprey

Hi @gduprey,

Firstly, I sincerely apologise for the significant oversight on my part regarding this issue that you opened so long ago.

If you're still having this problem, I'd like to better understand it and resolve it. To do so, could you please provide your enumeration class, or at the least a similar example that triggers the problem? (I noticed your code includes FICA, and I'm a bit confused by its role... shouldn't TaxTableType be the enum value?)

Also, could you please share exactly how you're calling has_enumeration_for from your model?

This would help me in reproducing the issue. Thanks!

lucascaton avatar Dec 24 '23 09:12 lucascaton

I'm closing this issue for now, due to the lack of response (and apologise again for taking so long to get back to you).

Feel free to ping me here if you think this is still an issue 👍

lucascaton avatar Jan 21 '24 03:01 lucascaton