当我有一个名为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
答案 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