1

我想确保进入这个对象的数字可以被 3 整除。如何使用模型上的验证来防止无效输入?

谢谢!

4

2 回答 2

3

尝试这个:

# your_model.rb
validate :only_valid_numbers

private

    def only_valid_numbers
        if (self.number % 3) != 0
            self.errors[:base] << "Number must be divisible by 3!"
        end
    end

请记住,这0 % 3将为 0,因此,如果您不想允许,请将 if 语句更改为:

if self.number != 0 and ...etc...
于 2012-07-06T16:57:26.927 回答
0

您可以为此编写自己的简单验证方法,如下所示:

validate :divisible_by_three

def divisible_by_three
  unless attribute%3 == 0
    self.errors.add(:attribute, "is not divisible by 3")
  end
end

我不认为任何内置的 rails 方法,所以这可能是最好的解决方案。

汤姆

于 2012-07-06T17:01:29.443 回答