问题
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.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
This gives me an error though:
undefined method `at_beginning_of_week'
What do I need to correct?
回答1:
at_beginning_of_week has been removed in Rails 3. You should use beginning_of_week but, be careful, it's an instance method. So you have to do something like:
Date.today.beginning_of_week
Furthermore, you can use a range and make your query very nice to read:
where(:purchase_date => Date.today.beginning_of_week..Date.today.end_of_week)
来源:https://stackoverflow.com/questions/8505997/scoping-date-attribute-for-this-week