我會做這樣的:
#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
我有點困惑。你想驗證'季度'attr? – caspg
我不知道。我需要驗證稱爲'date'的屬性。這個日期應該包含在一個值範圍內,這些值是從'quarter'屬性獲得的(不知何故)。 –