How can I find records where a date is within the current month using ActiveRecord?
I have a simple rails app that is like an event system which has a start_at
field and an end_at
field. I want to be able to display the events whose start_at
month fall at this present month. I defined a scope for this like below:
scope :this_months_event, lamda{where("start_at = ?" Time.zone.now.month)}
Whenever I try this out in my console window I get an empty array. I observed that the month of the start_at
field is not being fetched so it cannot find the start_at
month, so it returns empty instead.
Does anyon开发者_StackOverflow中文版e know a good way to do this or how can I pass the start_at
month so that when I call Event.this_months_event
, I get all the events for this present month and if possible a scope to fetch past events and another to fetch present events.
Your condition says that start_at should be exactly the value of Time.zone.now.month, which, as of this writing is 8. You want to compare start_at with the beginning and end of the month:
scope :this_months_event, lambda { where("start_at >= ? AND start_at <= ?",
Time.zone.now.beginning_of_month, Time.zone.now.end_of_month) }
I assume start_at
and end_at
are datetimes? If so, you'll need to do something slightly more sophisticated:
scope :this_months_event, lambda { where("EXTRACT(MONTH FROM start_at)) = ?", Time.zone.now.month) }
See http://www.postgresql.org/docs/9.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
精彩评论