pthorsson
pthorsson

Reputation: 341

Loop through years and months Ruby On Rails

I've been fighting with the code for some days now and I really can't get anything good out of it!

I'm making a blog archive and I'm looking for a way to get all years and months from created_at. Lets say I got like a number of posts from 2011, 2012 and 2013.

This "code" below is just an example for a structure I'm trying to build (this is just so you get an idea of what I want it to look like)

years.each do |y|
   puts y.created_at.year

      y.created_at.month.each do |m|
      puts m.created_at.month

          (And ye, posts for each months loops here)

      end

end

The output I'm after is something like:

2013
  May
    Name of post
    Name of post
  April
    Name of post
    Name of post
  Mars
    Name of post
    Name of post

2012
  December
    Name of post
    Name of post
  November
    Name of post
    Name of post
  October
    Name of post
    Name of post

I hope I made it clear enough! I'm sure It's much simpler than I'm thinking right now! Would really appreciate some help here!

Upvotes: 1

Views: 600

Answers (1)

Mori
Mori

Reputation: 27779

month, year = nil, nil
Post.order("created_at desc") do |post|
  if year != post.created_at.year
    year = post.created_at.year
    puts year
  end

  if month != post.created_at.month
    month = post.created_at.month
    puts "\t#{post.created_at.strftime("%B")}"
  end

  puts "\t\t#{post.name}"
end

Upvotes: 1

Related Questions