With some help, I was able to take a method that displays a word count for each day in a project and reduce it down to pretty much one database quere. Here’s the method
def project_range(project, start, finish, &blk)
words = project.words.where(:wrote_on => start..finish)
word_map = words.index_by(&:wrote_on)
for day in start..finish
word_count = word_map[day] ? word_map[day].quantity : 0
blk.call(day, word_count)
end
end
The original question is here:
Reducing database hits in Rails
Now though, we want to change the way users enter word counts for each day, however — we want to give them a chance to enter multiple counts for a day, instead of just one per day. This method, however, only returns the word count for the last day entered, not all the word counts for that specific day.
I tried changing index_by to group_by, but I got an undefined method error for quantity. So, my question is… how can I handle multiple entries for the same day, where there are two wrote_on objects for say, 5/4/2012?
group_byworked with another modification. Changes are commented out.