发现重叠范围Rails的记录 [英] Finding records that overlap a range in Rails

查看:123
本文介绍了发现重叠范围Rails的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个事件模型,有一个 starts_at ends_at 列,我想找到那个发生在一个范围的日期事件。

So, I have an Event model that has a starts_at and a ends_at column and I want to find events that take place in a range of dates.

我想出这个 named_scope 范围通常是一个月):

I've come up with this named_scope (range is typically a month):

named_scope :in_range, lambda { |range|
  {:conditions => [
    'starts_at BETWEEN ? AND ? OR ends_at BETWEEN ? AND ?',
    range.first, range.last, range.first, range.last]} }

这如预期的工作。

Which works as expected.

但是如果一个事件的一个月开始前它不会显示的范围后结束的月份。有没有办法找到这些事件以适当的方式?

But if an event starts the month before and ends the month after the range it won't show. Is there any way to find those events in a proper way?

推荐答案

有四种情况:

     Start    End
1.      |-----|
2.  |------|
3.  |-------------|
4.         |------|

您named_scope只得到例1,2和4。所以,你只需要需要添加:

Your named_scope only gets cases 1,2 and 4. So you just need need to add:

named_scope :in_range, lambda { |range|
  {:conditions => [
     '(starts_at BETWEEN ? AND ? OR ends_at BETWEEN ? AND ?) OR (starts_at <= ? AND ends_at >= ?)',
     range.first, range.last, range.first, range.last, range.first, range.last
   ]}
}

这篇关于发现重叠范围Rails的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆