I want to get models whom date is within a date range.
So I want to do something like
MyModel.find_all_by_field1_id_and_field2_id(value1, value2, :conditions => { :date => nb_days_ago..Date.yesterday })
The thing is, the date attribute of my model is a string (with the format “08-24-2010”), and I can’t modify this.
So to compare it to my range of dates, I tried this:
MyModel.find_all_by_field1_id_and_field2_id(value1, value2, :conditions => { Date.strptime(:date, "%m-%d-%Y") => nb_days_ago..Date.yesterday })
But I get an error that basically says that strptime can’t process the :date symbol. I think my solution is not good.
How can I compare my string to my range of dates ?
Thanks
First of all I do not envy your situation. That’s a pretty ugly date format. The only thing I can think of is to generate an array of strings, in that format, representing ALL the days between your starting date and your finish date, then use the SQL “IN” syntax to find dates in that set (which you can do from within ActiveRecord’s :conditions param).
For example, if you wanted to search to 10 days ago:
The idea is this should generate SQL with something like “… WHERE date IN (“08-24-2010”, “08-23-2010”, “08-22-2010”, “08-21-2010”, “08-20-2010”)