How to get the id value from a Rails model enum? -


trying understand how use enums manage different user status levels.

class user < activerecord::base   enum user_status: [:active, :pending, :trial] end 

so active 0, pending 1, , trial 2.

so if this:

user.active?  

this works fine, when setting value still doing this:

user.user_status = 0 

i hoping like:

user.user_status = user.userstatus.trial 

the point don't want have remember index each enum value is.

also, if change order or add more user_status values, index change , want prevent bugs me hardcoding values in codebase.

is there better way handle enum index values?

you can find answer simply reading documentation:

user.trial! 

will set status , update record. more variants can refer docs.


Comments