2011-11-19 52 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

相關問題