Scoping date attribute for this week?

こ雲淡風輕ζ 提交于 2020-01-29 10:06:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!