我想验证answer text fields
的输入(文本)我有四个答案字段。以下是我想要完成的验证。
我已编写以下代码,但它没有运行验证,我注意到我的代码中有很多重复。你能不能查看代码,让我知道它为什么不起作用。
validate :check_answer, :on => :create
def check_answer
a1 = answer_1.gsub(/[^\.\d+]/, '')
a2 = answer_2.gsub(/[^\.\d+]/, '')
a3 = answer_3.gsub(/[^\.\d+]/, '')
a4 = answer_4.gsub(/[^\.\d+]/, '')
if !(a1.empty?) || !(a2.empty?) || !(a3.empty?) || !(a4.empty?)
if a1.include?('.') || a2.include?('.') || a3.include?('.') || a4.include?('.')
errors.add :answer_choices, "should have decimal values." if a1.empty? || a2.empty? || a3.empty? || a4.empty?
end
a1 = a1.to_i
a2 = a2.to_i
a3 = a3.to_i
a4 = a4.to_i
if (a1 - a2 == 0..1) || (a1 - a3 == 0..1) || (a1 - a4 == 0..1)
errors.add :answer_choices, "can't be too close in number range."
elsif (a2 - a1 == 0..1) || (a2 - a3 == 0..1) || (a2 - a4 == 0..1)
errors.add :answer_choices, "can't be too close in number range."
elsif (a3 - a1 == 0..1) || (a3 - a2 == 0..1) || (a3 - a4 == 0..1)
errors.add :answer_choices, "can't be too close in number range."
elsif (a4 - a1 == 0..1) || (a4 - a2 == 0..1) || (a4 - a3 == 0..1)
errors.add :answer_choices, "can't be too close in number range."
end
end
end
答案 0 :(得分:0)
您正在测试减法的结果是否小于范围。你想要的是检查两个数字的差异是否在[-1,1]之内:
if (-1..1).include?(a1 - a2) || (-1..1).include?(a1 - a3) || (-1..1).include?(a1 - a4)
errors.add :answer_choices, "can't be too close in number range."
elsif (-1..1).include?(a2 - a3) || (-1..1).include?(a2 - a4)
errors.add :answer_choices, "can't be too close in number range."
elsif (-1..1).include?(a3 - a4)
errors.add :answer_choices, "can't be too close in number range."
end
Range对象有各种内置方法,用于测试包含等: http://www.ruby-doc.org/core-2.1.2/Range.html