[英]with_options condition giving undefined method error
I am trying to simplify my validations on a model. 我正在尝试简化对模型的验证。 Before trying to refactor using with_options in the model I had:
在尝试在模型中使用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
This works perfectly it passes the form step into the required_for_step? 它将表单步骤传递给required_for_step吗? function and returns a value based on the step of the form the user is on.
函数并根据用户所在表单的步骤返回值。 That means I'm accessing the 'step' properly.
这意味着我正在正确访问“步骤”。
I have about 30 fields for this model to validate conditionally (I've only shown one here to get rid of clutter, but using with_options would make my model much more organized and I'd be able to refactor the conditional statement. This is what isn't working: 我有大约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
The error this returns is: 返回的错误是:
undefined method `required_for_step?' for #<Class:0x007f82c2919438>
You cannot remove the -> { ... }
part from your conditions. 您无法从条件中删除
-> { ... }
部分。 That defines a lambda, a piece of that is called and evaluated when you validate a model. 定义了一个lambda,当您验证模型时会调用并评估该lambda。 Without the lambda the code runs immediately when the class is load (and never again later on).
没有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.