how to auto-generate a month-by-month archive links?

Hey there,

Does anyone know how best to create a list of links that will sort objects by the month in which they were created, and automatically add months as time goes on?

I have a method that can find the objects created on a certain day, month, or year, based on url parameters. My question is how to automatically generate the links that will pass my method the correct parameters, based on the current date, and stopping listing at some arbitrary date in the past (say May 2006).

I'm trying to mimic a typical blog-style archive, so if someone can advise for an easier way to do that, that would be cool, too.

Thanks very much!

I'm not totally sure, to be honest. What would the corresponding view code look like?

To perhaps give you a better idea of what I'm after, take a look at the archive links in the right sidebar of this blog: http://www.robbyonrails.com/

Thanks for the help. I really appreciate it!

OK, I've almost got it perfect.

I modified your code to also extract the year of the archive (your code works fine without this modification):

@archives = Post.find(:all, :select => "DATE_FORMAT(created_at, '%Y') as year, DATE_FORMAT(created_at, '%m') as month, COUNT(posts.id) as count", :group => "month", :order => "month DESC")   end

and display it with this

<% @archives.each do |archive| %> <%= link_to Time.parse(archive.month+ "/ 2007").strftime("%B"), "archive/"+archive.year+"/"+archive.month %> (<%= archive.count %>) <% end %>

But I get a NoMethodError on 'year' in the view. What am I doing wrong in adding the year?

Thanks.

So, my additional SQL syntax for 'year' is correct, right?

Don't worry about it, though. You've been very helpful. Thanks again.

I figured out my problem, and it works perfectly. Thanks Jamal!

Why not custom routes, and group_by?

See