Skip to content

Storing State on Model - Enhancements? #380

@ckorhonen

Description

@ckorhonen

I've recently implemented the approach recommended in the readme for storing the current state on my mode:

after_transition do |model, transition|
  model.state = transition.to_state
  model.save!
end

Very pleased with the results - based on benchmarks, I've seen a 40-50% improvement in my queries.

In doing so I had to change a lot of code which was using Model.in_state(:foo) to use the new column (Model.where(state: 'foo')) and ended up doing some meta programming to automatically create the scopes based on the state machine states.

I was wondering if you had ever considered incorporating something like this into the gem, and supporting this usage in a more robust way? Given the performance gains we have seen I feel like it could be of interest.

In terms of what I'm thinking would be ideal:

  1. In the State Machine class you would specify the column on the model which should be used to store the current state.
  2. If declared, the column value is automatically set after a transition.
  3. If declared, the in_state method would automatically use this column for querying.

Thoughts? If we feel this is useful, happy to work on a PR.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions