I’m looking for advice on the best way to populate a calendar.
Currently, I can think of two ways to do it:
Loop through each day on my calendar and request all items for that
day from the database in each iteration…which would be thirty or so
db queries per page load.
** this way is obviously quite db heavy
2)
Make one request for all events in the month and then loop through
each day on my calendar and then loop through all my results to find a
match.
** this way is quite ruby / processing heavy
I’m looking for advice on the best way to populate a calendar.
Currently, I can think of two ways to do it:
Loop through each day on my calendar and request all items for that
day from the database in each iteration…which would be thirty or so
db queries per page load.
** this way is obviously quite db heavy
2)
Make one request for all events in the month and then loop through
each day on my calendar and then loop through all my results to find a
match.
** this way is quite ruby / processing heavy
Which is better?
You should be able to order the results from #2 in such a manner that
each day comes out in sequence… thereby causing only one run through
the entire returned results, adding each event to each day as you reach
it.
Make one request for all events in the month and then loop through
each day on my calendar and then loop through all my results to find a
match.
** this way is quite ruby / processing heavy
This is also the way I went. I order the results by event date, then
I use ActiveSupport’s Enumerable #group_by to get a Hash for each
date.
Then, it’s a simple matter to run through each date:
controller
@events = Event.find(:all, :conditions => [‘date BETWEEN ? AND ?’, @start_date, @end_date], :order => ‘date’).group_by(&:date)
@events is a Hash where the key is the event’s date, and the value
is an Array of Event objects
view or helper
(@start_date … @end_date).each do |date|
render_events_for_date(date, @events[date]) # @events[date] is
possibly nil
end