通过Ruby on Rails验证方法的最佳方法是什么?

per*_*nce 7 ruby-on-rails

目前我有一个功能来检查出生年份是否正确:

  validates :birth_year, presence: true,
            format: {with: /(19|20)\d{2}/i }
Run Code Online (Sandbox Code Playgroud)

我还有一个检查日期是否正确的函数:

  validate :birth_year_format

  private

  def birth_year_format
    errors.add(:birth_year, "should be a four-digit year") unless (1900..Date.today.year).include?(birth_year.to_i)
  end
Run Code Online (Sandbox Code Playgroud)

是否可以将底部方法组合到validates顶部而不是我现在拥有的两个验证?

Mor*_*rty 13

你应该可以做这样的事情:

validates :birth_year, 
  presence: true,
  inclusion: { in: 1900..Date.today.year },
  format: { 
    with: /(19|20)\d{2}/i, 
    message: "should be a four-digit year"
  }
Run Code Online (Sandbox Code Playgroud)

请查看:http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates