I have been unable to find a precise way to accomplish a validation exception on my rails model when using state_machine.
I have as expected a state column in my model and process a validation of emails by passing a user from unverified to verified, simple enough.
My model contains a normal validation of passwords
validates :password, length: {minimum: 6}
validates :password_confirmation, presence: true
This validation is important, but when passing my user from an unverified to a verified state I run into problems with my model validation as I am only applying an update to a single column, but active record integration with state_machine seems to apply a record update.
The state_machine snippet:
state_machine :initial => :unverified do
event :verify do
transition :unverified => :verified
end
So the solution would seem to apply an exception to the model validation, I was drawn to :unless as a solution..
I implemented something that I have to say I did not understand fully, which seems to now have the effect of removing any validation on password, obviously making my state_machine process work, but not meeting my objective..
my changes where to add:
validates :password, length: {minimum: 6}, :unless => :proc_no_password_validation
validates :password_confirmation, presence: true, :unless => :proc_no_password_validation
and apply in a private method:
def proc_no_password_validation
Proc.new { |user| user.verify }
end
I have a feeling that directionally I am on the right track, but help to spot my mistake or issue or other solution would be much appreciated.
UPDATE So I have had some help from Jef on this, but my conclusion was that the model validation method exception route was wrong, I modified my state code as follows:
state_machine :state, :initial => :unverified, :action => :bypass_validation do
event :verify do
transition :unverified => :verified
end
event :unverify do
transition :verified => :unverified
end
end
and then a validation bypass on the state I am interested in ignoring
def bypass_validation
if self.changes['state'][1] == 'verified'
save!(:validate => false)
else
save!(:validate => true)
end
end