轨道状态机转换和警卫/验证
我似乎无法弄清楚如何使用状态机使验证正常工作。 IE 我想在允许新的发布状态之前进行某些验证:
转换,我正在使用的 gem 有一种保护方法,但我似乎不知道如何正确使用它进行多个验证。
尝试简单地应用基本验证,如下所示:
validate_presence_of :age, :if => :publish? #
https://github.com/qoobaa/transitions
更新:这似乎按照我想要的方式工作,但我的下一个问题是如何将所有验证集中在一起以简化我的方法?我觉得我让它变得比它应有的复杂得多,而且鲁棒性也低得多。有什么想法吗?
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_minimum_feature_tags
if feature_list.size < 4
return true
else
return false
end
end
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_minimum_feature_tags
if feature_list.size < 4
return true
else
return false
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 SimpleStateMachine 代码将如下所示:
With SimpleStateMachine the code would look like this: