Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scope last week by Date object [duplicate]

Possible Duplicate:
Scoping date attribute for this week?

I am trying to scope all of my Products for this week, so it should show all the products leading up to whichever day of the week.

class Product < ActiveRecord::Base
   attr_accessible :purchase_date

   def self.last_week # All prices of last week.
      where(:purchase_date => 1.week.ago)
   end

   create_table :products do |t|
      t.date :purchase_date
   end
end

This code renders nothing in the view though so what do I need to correct?


ANSWER

For some reason I had to add advance(:days => -1) to in order to also retrieve Monday as well. You may not have to do this though.

def self.last_week
    where(:purchase_date => 1.week.ago.beginning_of_week.advance(:days => -1)..1.week.ago.end_of_week).order("purchase_date desc")
end

UPDATED ANSWER

I had to do the advance(:days => -1) because of the Time zone I am in. I got rid of this by making sure I'm in my own Time zone. So now it can be normal as it should be:

def self.last_week
  where(:purchase_date => 1.week.ago.beginning_of_week..1.week.ago.end_of_week)
end

And it should work correctly ONLY if you go by the default Rails Time zone or you config your own:

app/config/environment/development.rb

config.time_zone = "Eastern Time (US & Canada)"

Good luck.

like image 785
LearningRoR Avatar asked Dec 14 '11 21:12

LearningRoR


1 Answers

This should do the trick:

scope :last_week, lambda { where("purchase_date >= :date", :date => 1.week.ago) } 

scope :past_week, lambda { where("purchase_date >= :start_date AND purchase_date <= :end_date", {:start_date => 1.week.ago, :end_date => 1.day.ago }) } 
like image 168
apneadiving Avatar answered Oct 14 '22 19:10

apneadiving