Ruby on rails 如何使用RubyonRails使用%operator验证数字
我想确定进入这个物体的数字可以被3整除。如何在模型上使用验证来防止无效输入 谢谢 试试这个:Ruby on rails 如何使用RubyonRails使用%operator验证数字,ruby-on-rails,ruby,Ruby On Rails,Ruby,我想确定进入这个物体的数字可以被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
# 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
您可以为此编写自己的简单验证方法,如下所示:
validate :divisible_by_three
def divisible_by_three
unless attribute%3 == 0
self.errors.add(:attribute, "is not divisible by 3")
end
end
我不认为有任何内置的rails方法,所以这可能是最好的解决方案
汤姆
validate :divisible_by_three
def divisible_by_three
unless attribute%3 == 0
self.errors.add(:attribute, "is not divisible by 3")
end
end