将Date和1.month.ago放在一起?

时间:2011-12-15 13:43:20

标签: ruby-on-rails ruby ruby-on-rails-3

当我有一个名为Date的日期属性并希望将其放在类方法中时,如何将1.month.ago:purchase_date放在一起?

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

控制台出现语法错误并将其删除Date.today与我的其他方法相比给出了空白结果:

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

3 个答案:

答案 0 :(得分:10)

只需1.month.ago即可,您无需将Date.today添加到1.month.ago,因为1.month.ago从今天开始

答案 1 :(得分:7)

你的日期语法有误,你可能想要使用这样的东西:

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

答案 2 :(得分:0)

也许:

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