query where date = Date.today with Rails, MySQL, and Active Record

后端 未结 3 1069
日久生厌
日久生厌 2021-02-12 23:11

I see in the Active Record docs, you can query for a date using a greater than / less than comparison. However, what if you want to select where date = Date.today or must I quer

相关标签:
3条回答
  • 2021-02-12 23:49

    I believe the following post is more relevent to you Rails ActiveRecord Find / Search by Date

    In your case, when you search with date with activerecord you might want to take the timezone conversions into consideration.

    When you use the below method

    Subscription.where("DATE(created_at) = ?", Date.today).count

    it uses Mysql's DATE function to parse the date and you will get UTC time as saved in Mysql by activerecord. If your rails app is using some other time zone, you will get wrong results.

    The correct way to use this would be avoid using any SQL functions, and instead use a range.

    Subscription.where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)

    This would fetch results with timezone conversions applied. Please let me know you anyone has a better solution for this.

    0 讨论(0)
  • 2021-02-13 00:09

    For me just works like this:

    @fisrt_payment_day = Invoice.where("DATE(date_first_payment) >= ?", Date.today - 1.day)
    
    0 讨论(0)
  • 2021-02-13 00:12

    I think this is a DUP of this question:

    How to select date from datetime column?

    Subscription.where("DATE(created_at) = ?", Date.today).count
    

    I'm pretty sure this works in MySQL and PostgreSQL, but I'm not sure if it's a SQL standard.

    Wikipedia seems to think TO_DATE would be the standard: http://en.wikipedia.org/wiki/SQL#Date_and_time

    That didn't work for me in PostgreSQL though.

    0 讨论(0)
提交回复
热议问题