rubymongoidpadrino

Mongoid check intersecting time frames on document update


I want to check if the time frame intersects with another one on a document update. It works on creation, but I'm having trouble to change anything.

This is what i have so far:

if Timetracking.where(:begin.lt => params[:timetracking][:end], :end.gt => params[:timetracking][:begin]) && Timetracking.find(params[:id]) != params[:id]
    @error = 'Time overlapping with another entry'
    render 'timetracking/edit'
else
    do update stuff
end

My basic idea was to check if the time overlaps and if the id is something else than the one I'm updating. I also tried another Query without success:

if Timetracking.where(:begin.lt => params[:timetracking][:end], :end.gt => params[:timetracking][:begin], :id.ne => params[:id])
    @error = 'Time overlapping with another entry'
    render 'timetracking/edit'
else
    do stuff
end

Now I'm a little bit stuck. Maybe someone could push me to the right direction, please. :) Oh, and I'm using Padrino.

Thank you.


Solution

  • I think you may have an error in your logic. Your code tests whether the new Timetracking is within an existing one, not whether it overlaps.

    So, you have 2 possibilities. I think you will need an or statement:

    1. It starts between another Timetracking's begin and end or
    2. It ends between another Timetracking begin and end

    Also, I suggest you write a few specs. It would make it much easier to see what is going on.

    The following is not correct. It will always be false:

    Timetracking.find(params[:id]) != params[:id]
    

    You want something like:

    Timetracking.where(:begin.lt ..., :id.ne => params[:id])