I have the following situation:
I have a table with employee schedules in it. I need to make sure that overtime work they are claiming doesn't overlap with scheduled work time. I have written a method in my events model to check for (date, time, day) overlap. This code works fine from the console however when I create an entry via the form the checking fails and it allows everything (bad and good).
Here is the appropriate code:
Model
def overlap? courses = Hash.new # This will hold schedule info
# The following line of code is necessary since the session # can't be accessed from the model.
id = Project.find(self.project_id).employee_id
day = Regexp.new(Day.find(self.day_id).code)
schedules = Schedule.find(:all, :conditions => ["employee_id = ?", id])
for entry in schedules courses["#{entry.course}"] = [entry.start_time, entry.end_time, entry.start_date, entry.end_date, "#{entry.days}"] end
courses.each_pair do |key, values| if ((self.date >= values[2]) && (self.date <= values[3])) if ((self.start_time > values[0]) && (self.start_time < values[1])) if (values[4] =~ day) return true end end if ((self.end_time > values[0]) && (self.end_time < values[1])) if (values[4] =~ day) return true end end end end
Controller
def create @event = Event.new(params[:event]) unless @event.overlap? # We need to make sure there is no conflict. if @event.save flash[:notice] = 'Event was successfully created.' redirect_to :action => 'list' else render :action => 'new' end end flash[:notice] = 'There was a problem with this event.' end
Here is a transcript of my console session:
@event = Event.new
=> #<Event:0x47d5ec0 @new_record=true, @attributes={"day_id"=>nil, "project_id"=>nil, "title"=>nil, "date"=>nil, "location"=>nil, "end_time"=>nil, "start_time"=>nil}>
@event.day_id = 1
=> 1
@event.project_id = 1
=> 1
@event.title = "Test"
=> "Test"
@event.date = "05/02/2007"
=> "05/02/2007"
@event.location = "France"
=> "France"
@event.end_time = "13:15"
=> "13:15"
@event.start_time = "16:00"
=> "16:00"
@event.overlap?
=> true
@event.day_id = 2
=> 2
@event.overlap?
=> false
It works perfectly here but not in the app. Any ideas would be greatly appreciated. I may be making bad assumptions here.
I'm assuming that the strings I'm providing at converted into the appropriate datetime objects, as I can compare them with data from the database via the console with no trouble.
The data that is being compared against in the schedule table was entered through the appropriate schedule view.
Thanks, Glen