Rails ActiveRecord Find / Search by Date

后端 未结 3 1276
醉话见心
醉话见心 2020-12-31 22:22

I am trying to find records by \'created_at\' date - the database column type is \'datetime\' and I am using the UI DatePicker from jQuery

my url look like this: \"

相关标签:
3条回答
  • 2020-12-31 22:49
    selected_date = Date.parse(params[:selected_date])
    # This will look for records on the given date between 00:00:00 and 23:59:59
    sh = SupportHistory.where(
           :created_at => selected_date.beginning_of_day..selected_date.end_of_day)
    

    Time Zones may be a concern you need to look into, but this should work if all your times are in the same time zone.

    0 讨论(0)
  • 2020-12-31 22:52

    A simple solution I use sometimes is to cast the date(time) field as text on the database rather than parse the string into date on application side. For your case that would be:

    where('CAST(created_at AS text) LIKE ?', params[:selected_date])
    

    Might not be the most effective on the database (depending on the context you use it in) but saves a lot of pita on the application side.

    0 讨论(0)
  • 2020-12-31 22:55

    I solved this problem by creating a method in model like below, Say, my model is ticket.rb

     def created_date
       self.created_at.to_date
     end
    

    then I queried like this,

     selected_date = Date.parse(params[:date])
    
     Ticket.all.map{|t| t if t.created_date == selected_date}.compact
    

    This gives me accurate results that matches with the chosen date by the user.

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