Brit200313
Brit200313

Reputation: 738

Select object based on date range

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.

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!

Upvotes: 1

Views: 789

Answers (3)

j-dexx
j-dexx

Reputation: 10406

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)

Upvotes: 0

penner
penner

Reputation: 2737

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.

Upvotes: -1

MrYoshiji
MrYoshiji

Reputation: 54882

You can use the following:

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

Upvotes: 2

Related Questions