Reputation: 87
I have searched for similar questions but what I found is quite different from what I am trying to achieve.
I'm trying to get the status of a given day which would be in the range of days between the start and end dates in the db.
Records:
#<Schedule id: 1, starts_at: "2015-10-03", ends_at: "2015-10-15", status: "Available">
#<Schedule id: 2, starts_at: "2015-10-16", ends_at: "2015-10-30", status: "Busy">
what is the best way to retrieve the status of the day where the date is "2015-10-9"?
Upvotes: 0
Views: 367
Reputation: 583
Considering your schedule.starts_at
and schedule.ends_at
are formatted date :
date = Date.new(2015, 10, 9)
# matching_date is going to return us the schedules where the date is matched
matching_dates = schedule.select{|schedule| schedule.starts_at < date && schedule.ends_at > date}
# now, the map method is going to return us the status for every given matching_dates
statuses = matching_dates.map(&:status)
Note that I speak in plural for matching_dates
and statuses
, because the select
method return us an array of all matching dates.
We could (and should, I guess :) ) do it by having a where
clause on our Schedule, which might be better, but less explicit in my opinion. Either way, we'll get a collection of matching dates.
Upvotes: 1