state-machines/state_machines

get value for state name?

arches opened this issue · 7 comments

My setup:

class Vehicle
  state_machine :state do
    state :parked, value: 0
  end
end

My goal is to turn :parked back into 0, for example:

Vehicle.state_value(:parked) # => 0

Can't find a method for it in the docs or some minor code inspection.... any ideas? Thanks!

I think this is doable. You can use an Enum to get the mapping.

....but how?

oh are you saying I can make my own enum outside of the state machine and then use the enum values to initialize the state machine?

You can do that, but i have no context why you will need that.
When you use value that the value that get stored in the database.

I'm not talking about an individual record, I want to turn the name directly into the value. How are you suggesting I use an enum to do that?

@arches see https://hackhands.com/ruby-on-enums-queries-and-rails-4-1/

Rails enums are a bit painful in that regard. In this case, you'd have to do Vehicle.states[:parked]

thanks..... still wondering if there's a way to do this via state machine though. If the answer is really to store the mapping outside state machine I have a bunch of options. Just hoping I don't have to duplicate the mapping since it's already defined inside the state machine.