views:

95

answers:

1

Hi,

I'm trying to reproduce this SQL query I used with ActiveRecord:

Post.all(:conditions => ["EXTRACT(MONTH from created_at) = ? AND EXTRACT(YEAR from created_at) = ?", month, year])

But since I'm converting everything to DataMapper I was looking for a way to do this...

Can anyone help?

+1  A: 

I presume since this is tagged with "ruby-on-rails" that you have ActiveSupport loaded. This will provide the Time#end_of_month helper method. With it you can rewrite your query as:

time = Date.new(year, month).to_time

Post.all(:created_at => time..time.end_of_month)

Not only is this simpler, it eliminates raw SQL from the query (so the query is more portable to things other than RDBMS), and most importantly it will probably perform much better than the other query. With EXTRACT the database will likely have to perform a full table scan to extract the year and month from created_at in every row, and then compare them against your expected values. If you have a large dataset, this could be a significant load on your DB. However, provided your created_at column is indexed, the above approach should be extremely efficient in comparison.

dkubb