日期范围基于年份和季度

时间:2015-06-24 10:51:17

标签: ruby-on-rails validation ruby-on-rails-4.2

我有一个属性"2015-1",我以字符串形式保存 - quarter,意思是2015年和第一季度。

如何在validates :date, presence: true, inclusion: { in: something_that_returns_the_range_from_quarter_attr } 范围内获取所有日期的范围?

我需要它进行包含验证:

Customer

1 个答案:

答案 0 :(得分:1)

我会这样做:

#i would do the validation like so
validates :date_in_quarter

def date_in_quarter
  if self.date.blank? || !self.quarter_date_range.include?(self.date)
    self.errors.add(:date, "is blank or not in allowed range")
  end
end 

#the validation uses this method which gets date range from quarter attribute
def quarter_date_range
  year, quarter = self.quarter.split("-").collect(&:to_i)
  start_month = ((3 * quarter) - 2)
  start_date = Date.parse("#{year}-#{start_month}-01")
  end_date = start_date + 3.months - 1.day
  start_date..end_date
end