Forum: Ruby on Rails return yr/mo archive of posts

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
44c645f2c3a008972d9904102bae09df?d=identicon&s=25 matthew collins (Guest)
on 2006-02-05 23:38
(Received via mailing list)
looking at ways to return an archive, by year/month

in the past, (via php) i'd do something like pull all the entries,
ordered by date and iterate through them, doing a check on the month and
year and adding them to an array if there was a change

that method doesn't really feel very fluid or rails-like.

any suggestions?
82476266af9d460415d8f1fc16bb54ed?d=identicon&s=25 Jarkko Laine (jarkko)
on 2006-02-06 09:49
(Received via mailing list)
On 6.2.2006, at 0.35, matthew collins wrote:

> looking at ways to return an archive, by year/month
>
> in the past, (via php) i'd do something like pull all the entries,
> ordered by date and iterate through them, doing a check on the
> month and year and adding them to an array if there was a change
>
> that method doesn't really feel very fluid or rails-like.
>
> any suggestions?

You probably want to extend your domain model with a specialized
finder method.

This is how it's done in Typo:

class Article < ActiveRecord::Base

   # Find all articles on a certain date
   def self.find_all_by_date(year, month = nil, day = nil)
     from, to = self.time_delta(year, month, day)
     Article.find_published(:all, :conditions => ["created_at
BETWEEN ? AND ?",
                                                  from, to],
                            :order => "#
{Article.table_name}.created_at DESC")
   end


protected

   def self.time_delta(year, month = nil, day = nil)
     from = Time.mktime(year, month || 1, day || 1)

     to   = from + 1.year
     to   = from + 1.month unless month.blank?
     to   = from + 1.day   unless day.blank?
     to   = to.tomorrow    unless month.blank?
     return [from, to]
   end

After that, you can just call Article.find_all_by_date with arbitrary
year/month/date values.

//jarkko




--
Jarkko Laine
http://jlaine.net
http://odesign.fi
This topic is locked and can not be replied to.