Active Record Question

Hi-

Say I am returning some collection of DateTime items and I only want
to compare the month. Is there a way to do this directly in the find?

Something like this...
@coll = Collection.find(:all, :conditions => ["date.month
= ?",Time.now.lat_month])

Thanks!

Say I am returning some collection of DateTime items and I only want
to compare the month. Is there a way to do this directly in the find?

Something like this...
@coll = Collection.find(:all, :conditions => ["date.month
= ?",Time.now.lat_month])

Well, if it's mysql you could do this:

:conditions => ["MONTH(date.month) = MONTH(?)", Time.now.last_month]

Note this will pull up *every* date with february as the month regardless of the year, not just feb 08.

May lose some database independence, but it will work. Just looks up the method for your particular database.

You could also change it to look for a date BETWEEN this AND that which all Db's support.

-philip

Perfect, thanks!

I like the range, so for simplicity, I did this:

beginLastMonth = Time.now.last_month.beginning_of_month
endLastMonth = Time.now.last_month.at_end_of_month

@col = Collection.find(:all, :conditions => ["start_time >= ? and
start_time <= ?",beginLastMonth,endLastMonth])

Just for my own style I'd have done:
beginLastMonth = Time.now.last_month.beginning_of_month
endLastMonth = beginLastMonth.at_end_of_month

Not only does it avoid figuring out last_month a second time, but in that tiny fraction of a second between the two lines the month could change and then you have a two month range.

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com