ZK Zhao
ZK Zhao

Reputation: 21523

Rails: How to loop through month?

I made a scope help me to select objects

  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

Then, I want to loop through this method, from 2014/1 to now. How can I do it?

Maybe something like this:

  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

I find a solution here, How to Loop through Months in Ruby on Rails. But it seems about looping through the days. Not the month

Upvotes: 1

Views: 1401

Answers (2)

yeyo
yeyo

Reputation: 3009

You could use the Date#next_month method

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

Upvotes: 1

Prakash Murthy
Prakash Murthy

Reputation: 13067

With the best_of_the_month scope defined to take month and year as params, the following code should work:

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

Upvotes: 1

Related Questions