Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Enum and want to access the stored integer value in the view

I'm using ActiveRecord's Enum to store the weekdays with the following:

enum weekday: %w(monday tuesday wednesday thursday friday saturday sunday)

When calling the attribute .weekday on the model instance I correctly get the weekday name, e.g. "monday".

How could I get the numeric value (i.e. 0) when I need that instead?

like image 239
Fellow Stranger Avatar asked Dec 14 '22 23:12

Fellow Stranger


2 Answers

Use my_object[:weekday], or, if you're in the object, just self[:weekday].

UPDATE: OR (as found by Ms Numbers): .read_attribute_before_type_cast(:weekday)

like image 78
pdobb Avatar answered May 05 '23 18:05

pdobb


What you would rather want to do is this:

model_instance.read_attribute(:weekday)

Cleaner, simpler, straight to the point.

like image 23
parreirat Avatar answered May 05 '23 20:05

parreirat