Rails自定义验证方法不起作用

时间:2014-07-04 02:21:13

标签: ruby-on-rails ruby

我想验证answer text fields的输入(文本)我有四个答案字段。以下是我想要完成的验证。

  • 如果一个答案字段具有十进制值,则所有四个答案字段也应具有十进制值。
  • 如果答案字段没有差异,或者答案字段中只有1个,则应显示错误。如果answer1字段的编号为10,则answer2字段的数字应为11,而不是错误。

我已编写以下代码,但它没有运行验证,我注意到我的代码中有很多重复。你能不能查看代码,让我知道它为什么不起作用。

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

1 个答案:

答案 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