with_options 条件给出未定义的方法错误

with_options condition giving undefined method error

我正在尝试简化对模型的验证。 在尝试在模型中使用 with_options 进行重构之前,我有:

# model    
validates :number_of_locations, presence: true, if: -> { required_for_step?(:business_details) }

def required_for_step?(step)
  return true if form_step.nil?
  return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
end

这非常有效,它将表单步骤传递到 required_for_step?函数和 returns 基于用户所处表单步骤的值。这意味着我正在正确访问 'step'。

我有大约 30 个字段供此模型有条件地验证(我在这里只显示了一个以消除混乱,但使用 with_options 会使我的模型更有条理而且我能够重构条件语句。这是行不通的:

# model
with_options :if => required_for_step?(:business_details) do |step|
  step.validates :number_of_locations, presence: true
end

def required_for_step?(step)
  return true if form_step.nil?
  return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
end

这个returns的错误是:

undefined method `required_for_step?' for #<Class:0x007f82c2919438>

您不能从条件中删除 -> { ... } 部分。它定义了一个 lambda,其中一部分在您验证模型时被调用和评估。如果没有 lambda,代码会在 class 加载时立即运行(以后再也不会)。

with_options :if => -> { required_for_step?(:business_details) } do |step|
  step.validates :number_of_locations, presence: true
end

private
def required_for_step?(step)
  form_step.nil? || 
    form_steps.index(step.to_s) <= form_steps.index(form_step)
end