轨道状态机转换&警卫/验证

时间:2011-02-22 09:11:11

标签: ruby-on-rails validation ruby-on-rails-3 state-machine transitions

我似乎无法弄清楚如何使用状态机正确运行验证。 IE我想在允许新的发布状态之前做一些验证:

过渡,我正在使用的宝石有一个防护方法,但我似乎无法弄清楚如何正确使用它进行多次验证。

尝试简单地应用基本验证:

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

1 个答案:

答案 0 :(得分:0)

使用SimpleStateMachine,代码如下所示:

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