1
votes

I need to define a custom month range as a project_year.

Rather than a year starting in January and ending at the end of December, I need to define a project_year as starting August 1st and ending on the last day of July.

I need to group all reports by project_year and then by month. Report has a report_month attribute(dateTime). Essentially I would need to display the reports like this:

Projects:

2015

August

September

October

November

Etc

2014

August

September

October

November

Etc

2013

August

September

October

November

Etc

I've been playing around with the Array.sample method, but without success.

reports = @station.reports.order("report_month asc")
range = reports.last.report_month.year..reports.first.report_month.year

range.to_a.each do |year|
  start = year.beginning_of_year + 7.months
  finish = (year.beginning_of_year + 1.year - 6.months).end_of_month
  yr = reports.sample{ |r| report.report_month >= start and <= finish }

  <h1><%= year.strftime("%Y")</h1>

  yr.each do |m|
    <h1><%= m.strftime("%b")</h1>
  end
end

I realize the above isnt appropriate view code, Im just trying to indicate the manner I was trying to use. Which became cumbersome and hard to troubleshoot. After struggling with this for a while I decided to ask here.

Ultimately my the ideal would be to use the group_by feature outlined here: http://railscasts.com/episodes/29-group-by-month Only instead using group_by project_year.

Is this possible with Rails? Or is there a better way to group by a custom month range?

1

1 Answers

0
votes

Does it help if you add a the customer field on the model such as quarter then use the group_by api.

def quarter
  "#{created_at.month/4}, #{created_at.year}"
end