如何在Rails 3.1中查找本月创建的记录?

kid*_*tal 12 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

任何人都知道在Rails 3.1中查找本月创建的记录的最佳查询?

Ale*_*tie 36

class Model
  scope :this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) }
end
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

Model.this_month
Run Code Online (Sandbox Code Playgroud)

  • 嗯,试试`BETWEEN`:`"created_at BETWEEN?AND?"` (2认同)

cle*_*lem 22

我更喜欢无SQL:

Model.where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month)
Run Code Online (Sandbox Code Playgroud)

或作为范围:

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