LearningRoR
LearningRoR

Reputation: 27192

Putting Date and 1.month.ago together?

How would I put Date and 1.month.ago together when I have a date attribute called :purchase_date and want to put it inside a class method?

def self.last_month # Show only products of last month.
  where(:purchase_date => Date.today.1.month.ago.end_of_month..Date.1.month.ago.beginning_of_month)
end

console gives a syntax error and taking it away Date.today gives me blank results compared to my other method:

def self.this_month # Show only products of this month.
   where(:purchase_date => Date.today.beginning_of_month..Date.today.end_of_month)
end

Upvotes: 10

Views: 16556

Answers (4)

New Alexandria
New Alexandria

Reputation: 7324

If the future time needs to be farther out, like in the case of planned subscription orders, remember to use .since

def self.next_quarter    # Show only product order in the next 3 months
   where(:purchase_date => Date.today.beginning_of_month..3.months.since)
end

Upvotes: 0

Maybe:

def self.this_month 
   where(:purchase_date =>(Date.today - 1.month)..Date.today
end

Upvotes: 0

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

You have mistake in your Date syntax, you might want to use something like this:

def self.last_month # Show only products of last month.
  where(:purchase_date => 1.month.ago.beginning_of_month..1.month.ago.end_of_month)
end

def self.this_month # Show only products of this month.
   where(:purchase_date => Date.today.beginning_of_month..Date.today.end_of_month)
end

Upvotes: 9

Marek Příhoda
Marek Příhoda

Reputation: 11198

Just 1.month.ago is enough, you don't need to prepend Date.today to 1.month.ago because 1.month.ago starts from today

Upvotes: 16

Related Questions