views:

188

answers:

3

I'm trying to count the number of rows in a certain table by datetime.

More specifically, by a certain month, but can't find the right way to write the conditions for it.

xxx.count(:all, :conditions=> :xxx => yyy)

I have a datetime yyy to compare with xxx, but only want to compare the year and month.

+1  A: 

This might work.

:conditions => ["month(date_field) = ? AND year(date_field) = ?", month, year]
Jim
thanks for the quick answer, that did the trick!
Saifis
+4  A: 

The more efficient way is like this:

range = Date.today.beginning_of_month..Date.today.end_of_month
Model.count(:conditions => {:date_field => range})

This will generate a range condition, which, if you have an index on the date_field will be very fast even for millions of rows.

dasil003
+2  A: 

I have a plugin/gem called by_star which you can install using just sudo gem install by_star if you have gemcutter.org as one of your sources.

This plugin allows you to do this:

Post.by_month("January", :year => 2009)

Which will return all records from the Post model from January 2009.

Ryan Bigg