在我的模型文件中,我正在尝试根据隐藏的表单值进行条件验证。看起来像:form_type_main?方法永远不会被调用,或者只是不起作用。我想做错了吗?
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
答案 0 :(得分:1)
您可以简单地定义这样的验证:
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