Finding records that overlap a range in Rails

前端 未结 2 1763
暗喜
暗喜 2020-12-15 22:23

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.

2条回答
  •  爱一瞬间的悲伤
    2020-12-15 23:20

    There are four cases:

         Start    End
    1.      |-----|
    2.  |------|
    3.  |-------------|
    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
       ]}
    }
    

提交回复
热议问题