【问题标题】:Rails 4 + Ransack: lteq does not work well with datetime?Rails 4 + Ransack:lteq 不适用于日期时间?
【发布时间】:2014-07-17 19:34:39
【问题描述】:

我有一个搜查表:

<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 %>

我希望用户能够输入 2 个日期,并且对于 start_date 大于或等于第一个文本字段且 start_date 小于或等于第二个文本字段的每个 ScheduledPayment 记录显示。

这行得通:

请注意,该记录的开始日期为 07/17/2014。当我在第二个文本字段中输入07/17/2014 时,什么都没有显示:

我猜这是因为该记录的 start_date 中的小时或分钟超过 +00:00:00,这可能是第二个字段的默认值。在这种情况下,我将如何获取 start_date 07/01/201407/17/2014 23:59:5907/17/2014 的绝对结尾)的所有记录?

【问题讨论】:

    标签: ruby-on-rails ransack


    【解决方案1】:

    您可以尝试以下方法吗?

    # 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)
    

    【讨论】:

    • 谢谢耀西。您帮助我意识到,实际上使用纯 SQL / ActiveRecord 可能会更好,而无需进行搜查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多