Can the initial state be validated?

35 views
Skip to first unread message

jo...@spacebabies.nl

unread,
Mar 20, 2012, 4:55:44 PM3/20/12
to pluginaw...@googlegroups.com
The state_machine gem really is a great piece of machinery, it works flawlessly.

I have one question though I couldn't easily find an answer to. Is is possible to perform a before_transition validation for the initial state?

My use case is this: I have an initial state of 'started' in a state machine for an Assignment model. Users can have many assignments. However, any given user can only have one assignment in the started state. I can't figure out how to accomplish this using State Machine. I've now solved it using an ActiveRecord callback, but I would rather have everthing controlled by State Machine.

I would appreciate any help.

The relevant code:

class Assignment < ActiveRecord::Base
  belongs_to :user
  validate :single_started, :on => :create
  state_machine :state, :initial_state => :started do
    # events omitted...
  end
  def single_started
    errors.add :base, "Only one started assignment allowed" unless user.allowed_assignment?
  end
end

Aaron Pfeifer

unread,
Apr 30, 2012, 7:45:50 AM4/30/12
to pluginaw...@googlegroups.com
Hey there -

I apologize for taking so long to get back to you and that no one was able to answer your question.  To answer your question, yes -- this is definitely possible.  I hope I'm understanding you correctly, but if you define state-driven validations, these will always get run regardless of whether you're dealing with a new record or not.  For example:

class Assignment < ActiveRecord::Base
  belongs_to :user  
  state_machine :state, :initial_state => :started do
    # ...
    state :started do
      validate :single_started
    end
  end
  def single_started
    errors.add :base, "Only one started assignment allowed" unless user.allowed_assignment?
  end
end

In this example, you're basically indicating that the single_started validation should get run whenever the state is :started.

Hope this helps!

Best,
Aaron
Reply all
Reply to author
Forward
0 new messages