【问题标题】:Rails - define custom yearRails - 定义自定义年份
【发布时间】:2015-12-06 22:14:34
【问题描述】:

我需要将自定义月份范围定义为 project_year。

我需要将 project_year 定义为从 8 月 1 日开始到 7 月的最后一天结束,而不是从 1 月开始到 12 月底结束的一年。

我需要按 project_year 然后按月对所有报告进行分组。报告有一个 report_month 属性(日期时间)。基本上我需要像这样显示报告:

项目:

2015

八月

九月

十月

十一月

等等

2014

八月

九月

十月

十一月

等等

2013

八月

九月

十月

十一月

等等

我一直在使用 Array.sample 方法,但没有成功。

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

我意识到上面的视图代码不合适,我只是想指出我尝试使用的方式。这变得繁琐且难以排除故障。在为此苦苦挣扎了一段时间后,我决定在这里问。

最终我的理想是使用此处概述的 group_by 功能: http://railscasts.com/episodes/29-group-by-month 仅使用 group_by project_year。

Rails 可以做到这一点吗?还是有更好的方法按自定义月份范围分组?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    如果您在模型上添加客户字段,例如 quarter 然后使用 group_by api,是否有帮助。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多