Skip to content

Instantly share code, notes, and snippets.

@djgraham
Created January 15, 2010 11:52
Show Gist options
  • Save djgraham/277997 to your computer and use it in GitHub Desktop.
Save djgraham/277997 to your computer and use it in GitHub Desktop.
#overlapping dates check validations
validate :start_date_must_be_before_end_date
validate :overlapping_dates
private
def start_date_must_be_before_end_date
if start_date > end_date
errors.add_to_base "Start date must be before end date"
end
end
def overlapping_dates
overlap_conditions = [ ' ( ( start_date >= :ad AND end_date <= :dd )
OR ( start_date <= :ad AND end_date >= :dd )
OR ( start_date <= :ad AND end_date > :ad )
OR ( start_date < :dd AND end_date >= :dd ) )
' + ( id != nil ? ' AND ( id != :self ) ' : '' ) + '
', { :ad => start_date, :dd => end_date, :self => id } ]
existing_discounts = Discount.find(:all, :conditions=>overlap_conditions)
errors.add_to_base("Dates overlap with existing discounts") if existing_discounts.size > 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment