ruby-on-rails 带条件的Rails验证

kjthegm6  于 2023-08-08  发布在  Ruby
关注(0)|答案(3)|浏览(165)

所以我有这个:

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


即使条件不满足,也会进行验证。我错过了什么?

0tdrvxhp

0tdrvxhp1#

我相信你可以用validates_presence_of

validates_presence_of :number_of_teams, if: :even_and_small?

字符串
validates_presence_of的相关Rails API文档

zzoitvuj

zzoitvuj2#

def even_and_small?
    # guard to bypass validation
    return if number_of_teams.nil? || number_of_teams > 20

    enter code here
    errors.add(:number_of_teams, :invalid) unless number_of_teams % 2 == 0
  end

字符串

guz6ccqo

guz6ccqo3#

#validate 
validates :even_and_small?

  # validation
  def even_and_small?
    errors.add(:number_of_teams, :not_present) if number_of_teams.nil?
    errors.add(:number_of_teams, :number_not_even) unless number_of_teams % 2 == 0
  end

字符串

相关问题