【问题标题】:Rails 4 find data where the date is the last day of the monthRails 4查找日期是本月最后一天的数据
【发布时间】:2015-03-09 22:18:23
【问题描述】:

使用 Rails 4,我有一组数据,我只想要日期在该月最后一天的数据点,任何月份,但只需要日期是该月最后一天的数据点。

下面我设置了@data 变量,我的所有统计数据都将其限制为日期为去年的统计数据。我还想将数据限制为仅包含日期为当月最后一天的统计信息。

编辑 - 注意开始日期是一个变量,可以通过参数改变

startdate = Date.1.year.ago
@data = Statistic.where(date: startdate..Date.today).all

有没有一种简单的方法可以添加另一个 .where 子句并为此使用 end_of_month?

【问题讨论】:

    标签: ruby-on-rails date ruby-on-rails-4 where


    【解决方案1】:

    将此scope 写入您的Statistics 模型中:

    scope :last_date_stats, ->(dates) { where(date: dates) }
    

    在您的StatisticsController 中填充一个dates 数组,然后使用范围查询获取特定数据:

    dates = (0..11).to_a.map { |n| n.months.ago.end_of_month }    
    @last_date_statistics = Statistics.last_date_stats(dates)
    

    【讨论】:

    • 或:dates = (0..11).to_a.map { |n| n.months.ago.end_of_month }
    • 这对我来说是正确的,但我没有得到任何返回的记录。我认为数据库中的日期是“日期”,但格式为 (2014-12-25)。
    • 这行得通,尽管对于我的实现,我需要格式为 2014-12-25 的日期。为此,我使用了 evanbikes 代码并修改为 ... Date.parse(n.months.ago.end_of_month.to_s) }
    • 我唯一的另一个问题是开始日期不应固定为一年,但我应该能够将参数传递给控制器​​类以设置开始日期。因此,我假设在构建日期数组之前,我需要计算从开始日期算起的月数。
    • no_of_months = (Date.today.year * 12 + Date.today.month) - (old_date.year * 12 + old_date.month)
    猜你喜欢
    • 2019-02-06
    • 2017-01-31
    • 2015-11-15
    • 2010-12-13
    • 2015-08-16
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多