Lanbo
Lanbo

Reputation: 15702

Find ActiveRecord objects by week in the year

I have reports with a date in them. Now I want to find all the reports by a given week of a year. What I have is this:

class Model < ActiveRecord::Base
  attr_accessible :date

  def self.find_by_week(week, year)
    Model.all.find_all do |model|
      model.date.year == year and model.date.s­trftime("%­W").to_i == week
    end
  end  
end

But I am afraid that this solution might be not very performant when the Software has accumulated the thousands of reports expected for it. Is there a better solution?

If it matters, I'm using SQLite3 in development, but the production DB will be a MySQL. Though I'd like a solution that is DB-independent, if possible...

Upvotes: 0

Views: 119

Answers (1)

Zach Kemp
Zach Kemp

Reputation: 11904

You can pass in a date range:

dates = Date.commercial(2012,40)..Date.commercial(2012,41)
Model.where(:date => dates)

There are more parameters available for Date.commercial - the above will give you Monday to Monday. To set more specific dates/times, have a look at the docs.

Upvotes: 2

Related Questions