Rails 3 query in multiple date ranges

Posted by NeoRiddle on Stack Overflow See other posts from Stack Overflow or by NeoRiddle
Published on 2012-04-06T10:29:09Z Indexed on 2012/06/05 16:40 UTC
Read the original article Hit count: 235

Suppose we have some date ranges, for example:

ranges = [
          [(12.months.ago)..(8.months.ago)],
          [(7.months.ago)..(6.months.ago)],
          [(5.months.ago)..(4.months.ago)],
          [(3.months.ago)..(2.months.ago)],
          [(1.month.ago)..(15.days.ago)]
         ]

and a Post model with :created_at attribute.

I want to find posts where created_at value is in this range, so the goal is to create a query like:

SELECT * FROM posts WHERE created_at 
    BETWEEN '2011-04-06' AND '2011-08-06' OR
    BETWEEN '2011-09-06' AND '2011-10-06' OR
    BETWEEN '2011-11-06' AND '2011-12-06' OR
    BETWEEN '2012-01-06' AND '2012-02-06' OR
    BETWEEN '2012-02-06' AND '2012-03-23';

If you have only one range like this:

range = (12.months.ago)..(8.months.ago)

we can do this query:

Post.where(:created_at => range)

and query should be:

SELECT * FROM posts WHERE created_at 
    BETWEEN '2011-04-06' AND '2011-08-06';

Is there a way to make this query using a notation like this Post.where(:created_at => range)?

And what is the correct way to build this query?

Thank you

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about query