ActiveRecord Scope for Date format

Currently, if I have a table that use Date format like this:

create_table “claims”, :force => true do |t| “lodged_date” “status_date”

t.datetime "created_on"

t.datetime “modified_on”


Then given I use ‘#where’ to get a selected result like this:

Claim.where(:lodged_date => 2.months.ago.beginning_of_month…1.months.ago.end_of_month)

And if I set my Timezone to Sydney, I will get a SQL that looks like this:

SELECT “claims”.* FROM “claims” WHERE “claims”.“lodged_date” BETWEEN ‘2013-03-31 13:00:00.000000’ AND ‘2013-05-31 13:59:59.999999’

Which is incorrect, because what I want is actually the claim that is lodged from 2013-04-01 to 2013-05-31

If I use following code:

Claim.where(:lodged_date => 2.months.ago.to_date.beginning_of_month…1.months.ago.to_date.end_of_month)

I will get the correct SQL like this:

SELECT “claims”.* FROM “claims” WHERE “claims”.“lodged_date” BETWEEN ‘2013-04-01’ AND ‘2013-05-31’

But the code will be a little bit cumbersome.

Do you think this should be ActiveRecord’s responsibility to convert time range to a date range if target column is a date column?


Leo Liang

No, I for one don’t. When you compare an integer and a float, you expect it to compare based on the most precise type, not the least precise.

As you have shown below, you can’t treat dates and times as the same thing, so you need to use whichever one you mean in your code.