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

后端 未结 14 1364
傲寒
傲寒 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 11:05

    For MySQL try this out

    Model.where("MONTH(date_column) = 12")
    Model.where("YEAR(date_column) = 2012")
    Model.where("DAY(date_column) = 24")
    
    0 讨论(0)
  • 2020-11-27 11:05

    In Postgresql v 11+(i've tested): below way works

    Model.where('extract(year  from date_column::date) = ?', desired_year)
    Model.where('extract(month from date_column::date) = ?', desired_month)
    Model.where('extract(day   from date_column::date) = ?', desired_day_of_month)
    
    0 讨论(0)
提交回复
热议问题