【问题标题】:strptime error with Rails 4Rails 4的strptime错误
【发布时间】:2016-03-17 03:09:44
【问题描述】:

我正在我的模型内部创建一个简单的验证,检查日期 (to_date) 是否早于当前日期。

用户提交to_date 的格式为%m/%d/%Y,例如03/15/2016

我的问题是 rails 给我一个 invalid date 错误,尽管我已经三次检查日期格式是否正确。

这是我的验证:

validate  :date_not_before_now

def date_not_before_now
  if Date.strptime(self.to_date, '%m/%d/%Y').strftime("%Y-%m-%d") < Time.now.localtime.strftime("%Y-%m-%d")
  errors.add(:dates, "should not be in the past.")
end

结束

任何帮助弄清楚为什么这不起作用将不胜感激。

【问题讨论】:

    标签: ruby-on-rails validation ruby-on-rails-4 activerecord


    【解决方案1】:

    验证日期时试试这个

    validates :date_field, presence: true, date: {on_or_before: :today}
    
    def today
      Date.today
    end
    

    【讨论】:

    • 感谢您的建议,但在我的情况下 on_or_before 不起作用,因为 to_date 是一个字符串,而不是日期时间。
    【解决方案2】:

    你可以试试这个。

    validate  :date_not_before_now
    
    def date_not_before_now
      if ( Date.strptime(self.to_date, '%m/%d/%Y') < Time.now.localtime.to_date)
        errors.add(:dates, "should not be in the past.")
      end
    end
    

    在控制台中尝试过并工作,请参见以下示例

    Date.strptime("03/15/2016", '%m/%d/%Y') < Time.now.localtime.to_date
    ## Output
    => true
    

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 2014-03-25
      • 2014-02-04
      相关资源
      最近更新 更多