rails state machine transitions & guards / validations
I can't seem to figure out how to make validations work correctly with a state machine. IE I'd like to do certain validations before allowing the new state of publish:
Transitions, the gem I'm using has a guard method but i can't seem to figure out how to use it correctly for more than one validation.
Tried simply applying basic validations like so:
validate_presence_of :age, :if => :publish? #
https://github.com/qoobaa/transitions
UPDATE: This seems to work like I want it to, but my next question is how can I lump all the validations together to simplify my method? I feel like I'm making it a lot more complicated than it could be and much less robust. Any ideas?
state_machine do
state :draft
state :active
state :offline
event :publish do
transitions :to => :active, :from => :draft, :on_transition => :do_submit_to_user, :guard => :publish?
end
end
def publish?
unless description.blank? || invalid_minimum_feature_tags || invalid_minimum_images
return true
else
errors.add(:description, 'cannot be blank') if description.blank?
errors.add(:feature_list, 'must contain at least 4 features') if invalid_minimum_feature_tags
errors.add(:photos, 'must exceed 4 to publish') if invalid_minimum_images
return false
end
end
def invalid_minimum_images
if photos.size < 4
return true
else
return false
end
end
def invalid_min开发者_JAVA技巧imum_feature_tags
if feature_list.size < 4
return true
else
return false
end
end
With SimpleStateMachine the code would look like this:
def publish
unless description.blank? || invalid_minimum_feature_tags || invalid_minimum_images
do_submit_to_user
else
errors.add(:description, 'cannot be blank') if description.blank?
errors.add(:feature_list, 'must contain at least 4 features') if invalid_minimum_feature_tags
errors.add(:photos, 'must exceed 4 to publish') if invalid_minimum_images
end
end
event :publish, :draft => :active
def invalid_minimum_images
...
end
def invalid_minimum_feature_tags
...
end
精彩评论