Conditional Validation RAILS MODEL

2019-09-10 01:17发布

问题:

In my model file, I am trying to make a conditional validation depending on a hidden form value. It seems like the :form_type_main? method never gets called, or just does not work. Want am I doing wrong?

  attr_accessor(:form_type,:field1,:field2,:field3,:field4)

  required_main = ["field1", "field2"]
  required_second = ["field3", "field4"]

  if :form_type_main?
    required = required_main
  else
    required = required_second
  end

  required.each do |i|
    validates_presence_of i
  end


  def form_type_main?
    form_type == "main"
  end

回答1:

You may simply define the validations like this:

REQUIRED_MAIN = [:field1, :field2]
REQUIRED_SECOND = [:field3, :field4]

validates_presence_of *REQUIRED_MAIN, if: :form_type_main?
validates_presence_of *REQUIRED_SECOND, unless: :form_type_main?

def form_type_main?
  form_type == "main"
end