DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Selecting An ActiveRecord Collection By Date With Inherited_resources

09.17.2009
| 877 views |
  • submit to reddit
        Select a collection of ActiveRecord objects based on a date given in a url, eg:

/news              => all articles
/news/2009         => all articles in 2009
/news/2009/05      => all articles in may 2009
/news/2009/05/04   => all articles on 4th may 2009

models/news_article.rb
named_scope :published_during, lambda { |date|
  unless date.empty?
    date_scope        = [nil,'year','month','day'][date.size]
    year, month, day  = date
    current = DateTime.now
    year  ||= current.year
    month ||= current.month
    day   ||= current.day
    start_date = DateTime.new(year.to_i,month.to_i,day.to_i).send("beginning_of_#{date_scope}").to_s(:db)
    end_date = DateTime.new(year.to_i,month.to_i,day.to_i).send("end_of_#{date_scope}").to_s(:db)
    {:conditions => "`published_at` BETWEEN '#{start_date}' AND '#{end_date}'"}
  else
    {:conditions => '1=1'}
  end
}

in routes.rb

map.connect 'news/*date',  :controller => 'news_articles'

in controllers/news_article_controller.rb

class NewsArticlesController < InheritedResources::Base

  protected

  # Scope all requests for a collection of news articles by date
  def collection
    @news_articles ||=  end_of_association_chain.published_during(params[:date])
  end

end