2011-12-14 130 views
1

我正在嘗試爲本週範圍內的所有產品,因此它應顯示所有產品導致本週的任何一天。本週的範圍日期屬性?

class Product < ActiveRecord::Base 
    attr_accessible :purchase_date 

    def self.this_weeks 
    where("purchase_date >= ?", Date.at_beginning_of_week - Date.at_end_of_week) 
    end 

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

這給了我一個錯誤,但:

undefined method `at_beginning_of_week' 

我需要做什麼來糾正?

回答

3

at_beginning_of_week已在Rails 3中刪除。您應該使用beginning_of_week,但要小心,它是一種實例方法。所以,你必須做一些事情,如:

Date.today.beginning_of_week 

此外,還可以使用範圍,讓您的查詢非常好的閱讀:

where(:purchase_date => Date.today.beginning_of_week..Date.today.end_of_week) 
+0

謝謝你的兩個答案,我將使用新的可讀辦法。 – LearningRoR 2011-12-14 14:55:04