Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

ruby - Finding records that overlap a range in Rails

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...