before_save callback throws error #175

yuszuv opened this Issue Apr 17, 2012 · 3 comments


None yet
3 participants

yuszuv commented Apr 17, 2012


here's a example that doesn't work (at least with Rails 3.2)

class Post < ActiveRecord::Base
has_one :schedule

before_save do
  publish! if !schedule

state_machine :state, :initial => :unpublished do
  event :publish do
    transition :unpublished => :published

  state :published
  state :unpublished

That throws

StateMachine::InvalidTransition: Cannot transition state via :publish from :published (Reason(s): State translation missing:

Is this a feature or a bug? And how could I get the intended behaviour?

Regards, Jan

@ghost ghost assigned obrie Apr 23, 2012

divniy commented Apr 27, 2012

Your post is marked as 'published' on moment when callback is trigered. Try this

event :publish do
transition :unpublished => :published, :published => same


obrie commented Apr 29, 2012

Hey @yuszuv -

The problem here is that you're calling publish! within a before_save callback. Don't forget that when you call publish! this, in turns, calls save on your object which calls your before_save callback again. As you can see, your object is going to transition first from unpublished to published and then attempt to publish yet again.

If you want your object transitioned on create, then you should put this in a before_create callback. Alternatively, you can set the state_event attribute to "publish" on initialization so that the object will be automatically transitioned on creation.

Hope this helps!

@obrie obrie closed this Apr 29, 2012

yuszuv commented Apr 30, 2012

Thanks a lot. To understand what I got wrong always helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment