Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice for gems like workflow or AASM

i would like to know how you guys use the workflow or the AASM gem in the controller if you want to update all attributes, but also need the workflow/AASM callbacks to fire properly.

currently, i use it like this:

  class ModelController < ApplicationController
    def update
      @model = model.find(params[:id])

      if params[:application]['state'].present?
        if params[:application]['state'] == "published"
          @model.publish!
        end
      end
      if @model.update_attributes(params[:application]); ... end
    end
  end

that does not feel right, what would be a better solution ?

like image 415
fluxsaas Avatar asked Jul 05 '11 10:07

fluxsaas


1 Answers

I usually define multiple actions that handle the transition from one state to another and have explicit names. In your case I would suggest you add a publish action:

def publish
  # as the comment below states: your action 
  # will have to do some error catching and possibly
  # redirecting; this goes only to illustrate my point
  @story = Story.find(params[:id])
  if @story.may_publish?
    @story.publish!
  else
   # Throw an error as transition is not legal
  end
end

Declare that in your routes.rb:

resources :stories do
  member do
    put :publish
  end
end

Now your route reflects exactly what happens to a story: /stories/1234/publish

like image 184
Wukerplank Avatar answered Sep 27 '22 22:09

Wukerplank