Transition callback fired in spite of failed general validation

62 views
Skip to first unread message

Gurpartap Singh

unread,
May 26, 2012, 2:56:32 PM5/26/12
to pluginaw...@googlegroups.com
Even when the following general validation[1] fails, the changed state_event param passed from the form triggers it's transition callbacks to be fired.

  validate :validate_name_change, :on => :update
  def validate_name_change
    if name.to_s != name_was.to_s
      errors.add(:name, "can't be changed")
      return false
    end
  end

[1] not inside the state_machine block.

What's the way out? Sorry I have been asking a lot here lately, but I guess my questions and their subsequent answers would help others in doubt.

Aaron Pfeifer

unread,
May 28, 2012, 11:26:43 AM5/28/12
to pluginaw...@googlegroups.com
Hey Gurpartap -

before_transition callbacks are run prior to validations.  after_transition callbacks are run after the record saves successfully.

There really aren't any transition callbacks that run after validations but prior to saving.

Hope this helps clarify things!

-Aaron

Gurpartap Singh

unread,
May 28, 2012, 9:42:54 PM5/28/12
to pluginaw...@googlegroups.com
Shouldn't the transition callbacks only run after validation, before and after save?

Aaron Pfeifer

unread,
May 28, 2012, 10:46:44 PM5/28/12
to pluginaw...@googlegroups.com
Validations need to run within the context of the state of a record.  In order for that to happen, the transition needs to start prior to validations getting run.  As a result, transition callbacks run prior to validations.

You can always customize this behavior using something like below, but I wouldn't recommend it.. (note that I haven't tested an implementation like this)

class Vehicle < ActiveRecord::Base
  ...
  state_machine :action => nil do
    before_transition {|vehicle, transition| ...}
    before_transition :save
    ...
  end
end

-Aaron
Reply all
Reply to author
Forward
0 new messages