acts_as_state_machine initial state instant save

Posted on 07/03/2008. Filed under: Technology | Tags: |

Beware when using the excellent acts_as_state_machine (AASM): the corresponding action to your initial state will be called AFTER creation of the record (i.e. it is added to the :after_create callbacks).

In particular consider the following:

 class User < ActiveRecord::Base

  acts_as_state_machine :initial => :active
  state :passive
  state :active,  :enter => :do_activate

  def do_activate
    self.activated_at = Time.now.utc
    self.deleted_at = self.activation_code = nil
  end

end u = User.create(attributes)
u.activated_at => nil

However, changing do_activate to include a call to save like this:

def do_activate
  self.activated_at = Time.now.utc
  self.deleted_at = self.activation_code = nil
  save # This is the all important change
end

Will work as expected (at least as I expected it to work..):

u = User.create(attributes)
u.activated_at => Fri Mar 07 16:59:05 UTC 2008
Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: