Saving a state column upon transition using rubyist-aasm (acts as a state machine)

What is the best way to keep the state of an object in the database when navigating using aasm? I thought this would happen automatically, but that doesn't seem to be the case.

(Edit: when I manually save the object, the status column is updated, but the save is not performed on transitions.)

I cannot find a lot of useful documentation for this plugin, so if you have a suggestion for an alternative implementation of a state machine with better documentation, this can also help.

+7
ruby-on-rails aasm acts-as-state-machine
source share
4 answers

If you call! the form of the transition event method, the state will be saved. For example, suppose you have an object with the following event:

class Book < ActiveRecord::Base # ... aasm_event :close do transitions :to => :closed, :from => [:opened] end # ... end 

A call to book.close will set the state to closed , but will not be automatically saved. Call book.close! sets the state * and * automatically saves the AR object.

+14
source share

As Colin says, AASM will save your changes for you. What Marcus said is wrong, except for the fact that the latest version of the gem has an error.

On line 180 lib / persistence / active_record_persistence.rb (you can get this by running gem: unpack), you should see a comment saying:

Writes state to the status column and is saved to the database using update_attribute (which bypasses the check)

However, in the code it actually causes persistence!

 unless self.save 

An error occurs when the base model does not validate because the default save method does not bypass validation. A quick fix would be to do this instead:

 unless self.save(false) 

Now transitions really save the new state in the database.

+4
source share

I believe that AASM will keep the state of the object after the transition. See Lines 180-189 in the file aasm / lib / persistence / active_record_persistence.rb

0
source share

I think you need to keep the transition if the effect you want. ActiveRecord (which sits on top) does not autosave design records.

You can do a save in

-3
source share

All Articles