Rails: 如何循环月份?

Rails: How to loop through month?

我做了一个scope帮我select个对象

  scope :best_of_the_month, ->(year, month) do
    time = Time.new(year, month)
    start_time = time.beginning_of_month
    end_time = time.end_of_month
    where("created_at > ? AND created_at < ?", start_time, end_time).where("likes > ?", 15).where("rating > ?", 4.85).order_by_rating.to_a.uniq(&:author)
  end

然后,我想从 2014/1 to now 开始循环执行此方法。我该怎么做?

可能是这样的:

  start_date = Date.create(2014,1).month
  end_date = Date.today.month
  @monthly_videos = []
  (start_date..end_date).each do |year, month|
    videos = Video.best_of_the_month(year, month)
    @monthly_videos << videos
  end

我在这里找到了解决方案,How to Loop through Months in Ruby on Rails。但这几天似乎在循环。不是月份

best_of_the_month 范围定义为以月份和年份作为参数,以下代码应该可以工作:

date = Date.new(2014,1,1)
@monthly_videos = []
while true
  videos = Video.best_of_the_month(date.year, date.month)
  @monthly_videos << videos
  date += 1.month
  break if date == Date.today.beginning_of_month
end

您可以使用 Date#next_month 方法

date           = Date.new(2014,1,1)
final_date     = Date.new(Date.today.year, Date.today.month)
@monthly_video = []

loop do
    @monthly_videos << Video.best_of_the_month(date.year, date.month)

    break if date == final_date
    date = date.next_month
end