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

时间:2012-09-26 23:17:56

标签: ruby-on-rails

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

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

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

  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

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

3 个答案:

答案 0 :(得分:12)

你应该可以这样做:

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"
  }

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

答案 1 :(得分:4)

:birth_year, presence: true,
             format: {
                       with: /(19|20)\d{2}/i 
                     }  
             numericality: { 
                             only_integer: true,
                             greater_than_or_equal_to: 1900,
                             less_than_or_equal_to: Date.today.year
                           }

答案 2 :(得分:1)

正则表达式

   /\A(19|20)\d{2}\z/

只允许1900年到2099年之间的数字

\ A - 开始字符串

\ z - 字符串结尾