How Do I Search Between a Date Range, Using the ActiveRecord Model?

12,959

I believe you can pass a Range object to ActiveRecord's find and get what you want:

ReportsThirdParty.find(:all, 
  :conditions => { 
    :site_id => site_id, 
    :campaign_id => campaign_id, 
    :size_id => size_id, 
    :row_date => start_date..end_date } )

Edit: If you're using Rails 3 you can expect to use something similar to:

ReportsThirdParty.where( 
  :site_id => site_id, 
  :campaign_id => campaign_id, 
  :size_id => size_id, 
  :row_date => start_date..end_date)

For more information on Rails 3 Active Record queries check out:
http://railscasts.com/episodes/202-active-record-queries-in-rails-3

Share:
12,959
Russ Bradberry
Author by

Russ Bradberry

I am the CTO at SimpleReach, the leading content data platform. I am responsible for designing and building out highly scalable, high volume, distributed data solutions. Prior to SimpleReach I built out an SSP that included automated ad-network optimization and inventory forecasting. Additionally, I managed the engineering efforts for one of San Diego's foremost web design firms and an employment and training organization that focuses its efforts on placing Veterans in positions that highlight their capabilities. I am a US Navy Veteran, a DataStax MVP for Apache Cassandra, and co-author of "Practical Cassandra" A developer's guide to Apache Cassandra

Updated on June 07, 2022

Comments

  • Russ Bradberry
    Russ Bradberry almost 2 years

    I am new to both Ruby and ActiveRecord. I currently have a need to modify and existing piece of code to add a date range in the select. The current piece goes like this:

    ReportsThirdparty.find(:all, :conditions => {:site_id=>site_id, :campaign_id=>campaign_id, :size_id=>size_id})
    

    Now, I need to add a range, but I am not sure how to do the BETWEEN or >= or <= operators. I guess what I need is something similar to:

    ReportsThirdparty.find(:all, :conditions => {:site_id=>site_id, :campaign_id=>campaign_id, :size_id=>size_id, :row_date=>"BETWEEN #{start_date} AND #{end_date}")
    

    Even if this did work, I know that using interpolation here would leave me subject to SQL injection attacks.