Mongoid检查文档更新时的相交时间帧

时间:2016-07-11 13:58:50

标签: ruby mongoid padrino

我想在文档更新时检查时间范围是否与另一个时间范围相交。它适用于创作,但我无法改变任何东西。

这是我到目前为止所做的:

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

我的基本想法是检查时间是否重叠,以及id是否是我正在更新的ID。我还尝试了另一个查询但没有成功:

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

现在我有点陷入困境。也许有人可以把我推向正确的方向。 :)哦,我正在使用Padrino。

谢谢。

1 个答案:

答案 0 :(得分:0)

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])