Wednesday, November 19, 2008

Rails date Range

Holy Shmoly! Sometimes Rails and ruby just blows me away,

Let’s assume you are trying to find a bunch of records between a time frame.


class Call < ActiveRecord::Base
named_scope :by_month, lambda { |d| { :conditions => { :date => d.beginning_of_month..d.end_of_month } } }
end


simply specify a range

and running (the named_scope )


this_months_calls = Call.by_month Date.today

And Rails will return all the calls that were recorded during the current month. Love it.

4 comments:

  1. named_scope :by_month, lambda { |d| { :conditions => ["MONTH(date) = ?", d.month ] } }

    (not applicable to postgresql but damn faster)

    ReplyDelete
  2. yeah well, i never really liked you :)
    i was never a fan of skinny Frenchmen, nor optimization :)

    ReplyDelete
  3. lol :)

    go, guyes go !!

    DM !!

    i always loves urs counterstrikes :)

    ReplyDelete
  4. @Jerome: Too bad that doesn't actually select a single month, it selects that month from all years. Fail!

    ReplyDelete

Tell me what you think