ActiveRecord Find By Year, Day or Month on a Date field

后端 未结 14 1504
傲寒
傲寒 2020-11-27 10:00

I have an ActiveRecord model that has a date attribute. Is it possible to utilize that date attribute to find by Year, Day and Month:

Model.find_by_year(201         


        
14条回答
  •  粉色の甜心
    2020-11-27 10:49

    I think the easiest way to do this is a scope:

    scope :date, lambda {|date| where('date_field > ? AND date_field < ?', DateTime.parse(date).beginning_of_day, DateTime.parse(date).end_of_day}
    

    Use it like this:

    Model.date('2012-12-1').all
    

    That will return all models with a date_field between the beginning and end of day for the date you send.

提交回复
热议问题