Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices for using AASM in a Rails API Controller

We are using acts_as_state_machine (AASM) in our Rails app to control flow of models from one state to the next in a traditional finite state-machine. We are building out an API for our application, and as part of that we'd like to be able to trigger state transitions when a Rails model is updated based on the state that is passed into the update Controller method by the API user.

A simplified version of the state-machine looks like this:

aasm :column => :state do
    state :proposed, :initial => true
    state :published
    state :retired

    event :publish do
      transitions :from => :proposed, :to => :published
    end

    event :retire do
      transitions :from => :published, :to => :retired
    end
end

One option is to use remote-procedure call (RPC) style, where we provide /model/{ID}/publish and /model/{ID}/retire style endpoints. This is fairly straight forward, but isn't very RESTful.

Another option we've considered is inspecting the parameters and transitioning based on the incoming state property of the model. This feels like a "better" approach in that our API is kept simpler for the consumer, but it adds a lot of complexity to the controller in terms of logic.

What's the best way to implement the triggering of AASM state events for a Rails API? Are we missing an option?

like image 974
Joel Hooks Avatar asked Nov 09 '22 03:11

Joel Hooks


1 Answers

personally, I tend to have two kinds of calls - straight class-REST calls and state transitions, the most common one being an enabled? I would use what's most intiuitive and not worry about it being un-RESTful esp because I find the state transitions can have a different set of logic. In other words RPC - style

like image 126
timpone Avatar answered Nov 15 '22 04:11

timpone