1
votes

Tech specs: ruby 2.1.5p273, Rails 4.2.3.

I have an array of Days that I want to loop through to pick the right Exits (model) that fall within a date range.

  • @exits has :start_date and :end_date

  • @days is an array of dates like:

    => [Sun, 06 Sep 2015, Sat, 12 Sep 2015, Tue, 15 Sep 2015, Fri, 18 Sep 2015, Sat, 19 Sep 2015, Sun, 20 Sep 2015, Wed, 23 Sep 2015]

I thought something like this would work:

@days.each do |day|
  @exits.where(:start_date..:end_date).include?(day)
end

but I get an error:

TypeError: Cannot visit Range

What is the best way to query an object that has a date range (between two fields) by comparing it against a single date? Thanks!

3
What database do you use? - Leo Brito
I've done something like this How to Answer[1] before. [1]: stackoverflow.com/questions/2381718/… - Adam Sommer
use Exit.where('? BETWEEN start_date AND end_date', date) - MrYoshiji

3 Answers

2
votes

You can use the following:

@days.each do |day|
  exits = Exit.where('? BETWEEN start_date AND end_date', day)
  # etc.
end
0
votes

If you don't want to loop over them then you can do:

Event.where("start_date IN (:days) AND end_date IN (:days)", { days: @days })

or

Event.where(start_date: @days, end_date: @days)

-1
votes
Exit.where(day: @[email protected]_date)

or 

Exit.where('day >= ? AND day <= ?', @exit.start_date, @exits.end_date)

Doing SQL queries in a loop is probably a bad idea, it could be refactored to be be one call most likely. And this should happen in the controller not in the view.