Rails ActiveRecord - how to fetch records between two dates

后端 未结 8 1242
执念已碎
执念已碎 2020-12-29 23:16

I have in the database two date columns - from_date and to_date.

Example:

  • from_date: 2012-09-10
相关标签:
8条回答
  • 2020-12-29 23:39

    This should do the trick.

    today = Date.today
    
    data = ModelName.where("from_date <= ? AND to_date >= ?", today, today)
    
    0 讨论(0)
  • 2020-12-29 23:42

    Check the Rails guides on Range conditions:

    Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
    

    That will produce the following SQL:

    SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
    
    0 讨论(0)
  • 2020-12-29 23:47
    data = ModelName.find(:all, :conditions => "today >= from_date and today <= to_date")
    
    0 讨论(0)
  • 2020-12-29 23:49
    data = ModelName.where("today >= from_date AND today <= to_date")
    
    0 讨论(0)
  • 2020-12-29 23:50

    A secure and easy way to do this would be:

    Model.where(':date BETWEEN from_date AND to_date', date: Date.current)
    
    0 讨论(0)
  • 2020-12-29 23:53

    You could use below gem to find the records between dates,

    This gem quite easy to use and more clear By star am using this gem and the API more clear and documentation also well explained.

    ModelName.between_times(Time.zone.now - 3.hours,  # all posts in last 3 hours
                      Time.zone.now)
    

    Here you could pass our field also ModelName.by_month("January", field: :updated_at)

    Please see the documentation and try it.

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