所以我有这个:
class Calendar < ApplicationRecord
validates :number_of_teams, presence: true, if: :even_and_small?
has_many :matches
has_many :days
belongs_to :championship
def even_and_small?
number_of_teams <= 20 &&
number_of_teams % 2 == 0
end
字符串
我只想在number_of_teams
属性小于20且为偶数时验证它。但是当我在irb上尝试的时候:
2.7.0 :004 > c.championship_id = 1
2.7.0 :005 > c.number_of_teams = 33
2.7.0 :006 > c.valid?
Championship Load (0.2ms) SELECT "championships".* FROM "championships" WHERE "championships"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> true
型
即使条件不满足,也会进行验证。我错过了什么?
3条答案
按热度按时间0tdrvxhp1#
我相信你可以用
validates_presence_of
字符串
validates_presence_of的相关Rails API文档
zzoitvuj2#
字符串
guz6ccqo3#
字符串