DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Selecting An ActiveRecord Collection By Date With Inherited_resources

Snippets Manager user avatar by
Snippets Manager
·
Sep. 17, 09 · · Code Snippet
Like (0)
Save
Tweet
697 Views

Join the DZone community and get the full member experience.

Join For Free
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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • An Overview of Key Components of a Data Pipeline
  • Pattern Matching for Switch
  • How to Utilize Python Machine Learning Models
  • SDLC Vs STLC: What's the Difference?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo