2011-11-19 54 views

回答

34
class Model 
    scope :this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) } 
end 

你可以这样调用:

Model.this_month 
+0

整洁干净,+1 – apneadiving

+0

做到这一点干活的SQLite?我试图在sqlite中运行它并抛出 ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:near“<”:语法错误:SELECT“orders”。* FROM“orders”WHERE(created_at>'2011-11- 01 04:00:00.000000'和<'2011-12-01 04:59:59.999999') \t from /Users/mrchess/.rvm/gems/ruby-1.9.2-p290/gems/sqlite3-1.3.4 /lib/sqlite3/database.rb:91:in'initialize' – kidcapital

+2

嗯,试试'BETWEEN':''created_at BETWEEN?AND?“' –

3

取决于如果您寻找所有型号的所有记录或特定模型等等

对于单一的模型,你可以这样做:

User.where('created_at >= ? and created_at <= ?', Time.now.beginning_of_month, Time.now.end_of_month) 
21

我更喜欢SQL-少:

Model.where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) 

或作为范围:

class Model < ActiveRecord::Base 
    scope :this_month, -> { where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) } 
end 
2

提供scope实施例中的答案是错误的。 Rails使用范围的热切评估,因此Time.now.beginning_of_month将始终是范围初步评估的月份的开始。在范围中使用日期的正确方法是将lambda传递给scope

class Model < ActiveRecord::Base 
    scope :this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) } 
end 

在Rails 4米范围必须使用一个可调用的对象,如LambdaProc

相关问题