John
John

Reputation: 6612

Determine day in date

I have an activity model which has an activity date. Now I am iterating day numbers and I want to show the activity from a collection of activities which has that day number. Something like this:

1 activities = Activity.all
2 (1..31).each do |day|
3   activity = activities.where(activity_date.day == day)
4   unless activity.blank?
5     ..show activity data...
6   end
7 end 

The issue is with line 3, which doesn't work obviously. What is the best way of doing this?

Upvotes: 0

Views: 60

Answers (1)

pawurb
pawurb

Reputation: 526

You can use MySql dayofmonth() function:

activity = Activity.where("dayofmonth(created_at) = ?", day).first

Like this it will only fetch necessary records from db.

Note that even if you have more than one activities in that day it will only select the first one.

Upvotes: 2

Related Questions