Over a million developers have joined DZone.

Selecting An ActiveRecord Collection By Date With Inherited_resources

·
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
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}