birthday icon indicating copy to clipboard operation
birthday copied to clipboard

How would I sort by birthday field ?

Open borisreitman opened this issue 12 years ago • 3 comments

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.

borisreitman avatar Nov 13 '12 17:11 borisreitman

Trying to figure out the same issue, have you resolved it?

timvoet avatar May 30 '14 12:05 timvoet

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

nextgenappsllc avatar Dec 13 '16 20:12 nextgenappsllc

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 %>

ThomasConnolly avatar Jul 10 '20 17:07 ThomasConnolly