簡體   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