Rails 4 + Ransack: lteq does not work well with datetime?
Asked Answered
G

1

6

I have a ransack search form:

<h1>Scheduled Payments</h1>


<%= search_form_for [:admin, @search] do |form| %>
  <%= form.text_field :start_date_gteq, value: @order_date_gteq_with_proper_format, class: "datepicker" %> to
  <%= form.text_field :start_date_lteq, value: @order_date_lteq_with_proper_format, class: "datepicker" %>
  <%= form.submit "Search" %>
<% end %>

I want the user to be able to type in 2 dates, and for every ScheduledPayment record with start_date greater than or equal to the 1st text field AND start_date less than or equal to the 2nd text field to show up.

This works:

enter image description here

Notice that that record has a start date of 07/17/2014. When I type 07/17/2014 in the 2nd text field, nothing shows up:

enter image description here

I'm guessing it's because the hours or minutes in the start_date of that record is more than +00:00:00, which is probably what is used as the default for the 2nd field. In this case how would I grab all records with start_date 07/01/2014 to 07/17/2014 23:59:59 (the absolute end of the 07/17/2014)?

Gastrin answered 17/7, 2014 at 19:34 Comment(0)
M
5

Can you try the following?

# the controller's action where you pass the params to the search method:
def your_action
  start_time = params[:start_date_gteq].to_date rescue Date.current
  start_time = start_time.beginning_of_day # sets to 00:00:00
  end_time = params[:start_date_lteq].to_date rescue Date.current
  end_time = end_time.end_of_day # sets to 23:59:59
  ScheduledPayment.search(start_time: start_time..end_time)
Maiga answered 17/7, 2014 at 20:14 Comment(1)
Thanks Yoshi. You helped me realize that it might actually be better just to use pure SQL / ActiveRecord for this, without ransack.Gastrin

© 2022 - 2024 — McMap. All rights reserved.