Shp*_*ord 0 activerecord datetime scope ruby-on-rails ruby-on-rails-3
我有以下范围:
scope :this_month, :conditions => ["created_at >= ?", Date.today.beginning_of_month]
Run Code Online (Sandbox Code Playgroud)
这使得SQL输出a.response_sets.this_month.to_sql:
SELECT "response_sets".* FROM "response_sets" WHERE created_at >= '2012-05-01'
Run Code Online (Sandbox Code Playgroud)
但由于今天实际上是6月1日,那个日期似乎是错误的.所以,我试图绕过范围并直接做一个条件,如下:
a.response_sets.where(["created_at >= ?", Date.today.beginning_of_month]).to_sql
Run Code Online (Sandbox Code Playgroud)
然后,输出:
SELECT "response_sets".* FROM "response_sets" WHERE created_at >= '2012-06-01'
Run Code Online (Sandbox Code Playgroud)
哪个是对的.那么为什么Date.today.beginning_of_month在范围内进行直接进行where呢?
在范围中使用日期时,您应该使用lambda,以便在每次调用范围时对范围进行评估:
scope :this_month, -> { where("created_at >= ?", Date.today.beginning_of_month) }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |