runchu
runchu

Reputation: 151

How check time overlaps in rails

I created a model: Lecture(start_time, end_time, location). I want to write validation functions to check wether the new lecture's time overlapping with saved lectures in database. So that I can find out if the location is occupied in that time. My function is:

class Lecture < ActiveRecord::Base

validates :title, :position, presence: true

validates :start_time, :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
         message: "Incorrect time format" }

validate: time_overlap

def time_overlap
    Lecture.all.each do |user| 
       if (user.start_time - end_time) * (start_time - user.end_time) >= 0                       
       errors.add(:Base, "time overlaps")
       end
     end 
end

end

The error message: NoMethodError in LecturesController#create undefined method `-@' for nil:NilClass. How to write this function in right format?

Upvotes: 0

Views: 737

Answers (2)

Navid Khan
Navid Khan

Reputation: 1169

Lets say you have two slots of time, as:

start_time_a
end_time_a
start_time_b
end_time_b

There are three possible cases where there can be an overlap between the two time slots.

1) start_time_b >= start_time_a && start_time_b =< end_time_a ( i.e, slot b starts somewhere in the middle of slot a )
2) end_time_b >= start_time_a && end_time_b <= end_time_a ( i.e, slot b ends somewhere between slot a )
3) start_time_b <= start_time_a && end_time_b >= end_time_a ( i.e, slot b is larger than slot a, and completely covers it.

If you check for these three conditions, you can determine if there's an overlap between two time slots.

Conditions 1 & 2 can be simplified using start_time_b.between?(start_time_a, end_time_a).

Upvotes: 1

Yorkshireman
Yorkshireman

Reputation: 2343

Take a look at Ruby 2.3.0's Time class: http://ruby-doc.org/core-2.3.0/Time.html

You can use it to check if a Time instance is before or after another Time instance, such as:

t1 = Time.now
t2 = Time.now
t1 < t2
=> true
t1 > t2
=> false

So, to check if a given time would exist during an existing Lecture in the database, you could write some Ruby to check if the proposed Lecture's start time or finish time sits after the start time AND before the end time of any existing Lectures.

Upvotes: 1

Related Questions