繁体   English   中英

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吗? 函数并根据用户所在表单的步骤返回值。 这意味着我正在正确访问“步骤”。

我有大约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

返回的错误是:

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

您无法从条件中删除-> { ... }部分。 定义了一个lambda,当您验证模型时会调用并评估该lambda。 没有lambda,代码将在加载类时立即运行(以后不再运行)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM