首页 > 解决方案 > 如何验证rails中的时间戳?

问题描述

我对 Rails 很天真,我试图to_date_timestamp通过使用下面提到的代码来验证Transaction::ListingIntr。我想检查 to_date_timestamp,我的要求是 to_date_timestamp 应该小于当前时间戳。这个代码在本地机器上运行良好。但是,当我将其部署在生产价值上时,Time.zone.now.to_i + 1 始终固定为我部署代码(用于less_than_or_equal_to: Time.zone.now.to_i + 1)的时间。无法弄清楚为什么会发生这种情况。请帮助我。

class Transactions::ListingIntr < ApplicationInteraction
  object :user
  string :type, :sort_by, :query, default: nil
  integer :from_date_timestamp, :to_date_timestamp, default: nil
  string :currency, default: nil


  validates :to_date_timestamp,
            numericality: { greater_than: 0, less_than_or_equal_to: Time.zone.now.to_i + 1, allow_blank: true }

end

标签: ruby-on-rails

解决方案


您可以尝试添加custom validation将 time 转换为 firstutc然后它将 validate to_date_timestamp

validate :check_to_date_timestamp 

def check_to_date_timestamp
  if to_date_timestamp.present? && (to_date_timestamp.utc.to_i < 0 || to_date_timestamp.utc.to_i > Time.now.utc.to_i + 1)
    errors.add(:base, "to_date_timestamp is not valid")
  end            
end

推荐阅读