我想查找今天用Ruby on Rails创建的所有记录,例如Posts,然后查找昨天创建的所有Post,依此类推……我该怎么办?
谢谢,
凯文
试试这个:
#Today
Posts.find(:all, conditions: { :created_at => Date.today...Date.today + 1 })
#Yesterday
Posts.find(:all, conditions: { :created_at => Date.today - 1...Date.today })
或这样(我认为最好):
#Today
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today] )
#Yesterday
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today - 1] )
最近,我发现Date.today可以等于Date.tomorrow,而Date.today可以等于Date.yesterday,具体取决于时区设置。Date.today使用装箱时间(通常是utc),而Date.tomorrow和昨天使用Time.zone,所以要小心。Date.current使用Time.zone,应代替Date.today使用