简体   繁体   中英

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:

# 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? 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:

# 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. Without the lambda the code runs immediately when the class is load (and never again later on).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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