时间戳轨的自定义验证

时间:2018-12-11 13:37:31

标签: ruby-on-rails ruby

我有一个小问题。任何人都可以回答如何正确验证此案?也许需要将时间戳转换为整数或其他形式?

模型:unworked_day.rb

class UnworkedDay < ApplicationRecord
  validate :end_date_after_start_date?

  def end_date_after_start_date?
    if unworked_period_to.to_i < unworked_period_from.to_i
       errors.add :unworked_period_to, "Unworked period to should be greater than the unworked period from"
    end
  end

迁移

  t.timestamp :unworked_period_from
  t.timestamp :unworked_period_to

1 个答案:

答案 0 :(得分:1)

您可以像这样直接比较两个时间戳对象,

  def end_date_after_start_date?
    if unworked_period_to < unworked_period_from
       errors.add :unworked_period_to, "Unworked period to should be greater than the unworked period from"
    end
  end

无需转换任何其他data_type