birthday
birthday copied to clipboard
How would I sort by birthday field ?
So in the sorting, I don't care about the year, I want to see what is coming up in terms of days and months.
Trying to figure out the same issue, have you resolved it?
What I do is I use the date range as the guide for birthdays. The following is the code for the JSON API controller action for birthdays:
def birthdays
date_range = params[:start].to_date..params[:end].to_date
employees = User.find_birthdays_for(params[:start], params[:end])
employees_by_birthday = employees.inject({}) do |hash, employee|
next hash if employee.birthday.nil?
bday = employee.birthday.strftime('%m%d')
arr = hash[bday] || []
arr << employee
hash[bday] = arr
hash
end
@birthdays = []
date_range.each do |date|
key = date.strftime('%m%d')
employees_by_birthday[key]&.each do |employee|
@birthdays << {title: employee.common_name, start: date}
end
end
end
If you want all and to sort them by birthdays then just fetch them all then sort using strftime('%m%d')
on the birthday in the sort method
I use a birthday helper to strip out the year for sorting purposes
module BirthdaysHelper def birthdays_this_week Member.find_birthdays_for(Date.today.beginning_of_week, Date.today.end_of_week).order(:birthday.strftime ('%m%d')) end end
then in the view:
<% birthdays_this_week.each do |member| %>
<%= member.first_name. titleize %> <%= member.last_name.titleize %>, <%= member.birthday.strftime("%B %-d") %>
<% end %>