dexx1220
dexx1220

Reputation: 101

Rails custom validation has errors but still saving?

I'm creating a rails app to manage events and I want to add validation to check if an event overlaps with another.

Here's my custom validation code to check for overlapping events:

class Event < ActiveRecord::Base
  attr_accessible :full_date, :start_hour, :end_hour, :address

  validate :no_overlapping_events

  def no_overlapping_events
    overlap = false
    same_date = Event.where(:full_date => self.full_date).where("id != ?", self.id).where(:address => self.address)


    same_date.each do |t|
      if self.start_hour <= t.start_hour
        if self.end_hour >= t.start_hour
          overlap = true
          break
        end
      end 
    end

    if overlap == true
      errors.add(:base, "Can't have overlapping events!")
    end
  end
end

I can still create events that are overlapping and they're still being saved. What am I doing wrong here?

Upvotes: 2

Views: 650

Answers (1)

Adnan
Adnan

Reputation: 2967

Your custom validation method "ends" too soon. Try:

class Event < ActiveRecord::Base
  attr_accessible :full_date, :start_hour, :end_hour, :address

  validate :no_overlapping_events

  def no_overlapping_events
    overlap = false
    same_date = Event.where(:full_date => self.full_date).where("id != ?", self.id).where(:address => self.address)

    same_date.each do |t|
      if self.start_hour <= t.start_hour
        if self.end_hour >= t.start_hour
          overlap = true
          break
        end
      end 
    end

    if overlap == true
      errors.add(:base, "Can't have overlapping events!")
    end
  end
end

Also, as a logic error, what about the case when:

self.start_hour > t.start_hour and self.start_hour < t.end_hour

Upvotes: 3

Related Questions