找到你要的答案

Q:date range based on year and quarter

Q:根据日期和季度的日期范围

I have an attribute quarter, which I save in a string form - "2015-1", meaning year 2015 and first quarter of the year.

How can I get the range of all dates within this quarter?

I need it for inclusion validation:

validates :date,
    presence: true,
    inclusion: { in: something_that_returns_the_range_from_quarter_attr }

我有一个属性的季度,我保存在一个字符串的形式”,意思2015-1”2015年第一季度。

我怎样才能得到本季度内所有日期的范围?

我需要它包含验证:

validates :date,
    presence: true,
    inclusion: { in: something_that_returns_the_range_from_quarter_attr }
answer1: 回答1:

I would do it like this:

#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

我会这样做的:

#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
ruby-on-rails  validation  ruby-on-rails-4.2