【问题标题】:How can I search for dates using Ransack in rails如何在 Rails 中使用 Ransack 搜索日期
【发布时间】:2021-07-01 14:18:09
【问题描述】:

我在 Rails 中使用 Ransack。我完全愿意把它拿出来并使用一些不同的东西,这些东西可能会更好地处理日期。我只是使用了ransack,因为我对它有点熟悉。 Db 是 Postgres。

我有一个带有“check_out_date”列的订单模型。

我只是想搜索具有特定日期的订单。

这是我的表格:

    <%= search_form_for @q do |f| %>
    <%= f.date_field :check_out_date_cont  %>
    <%= f.submit 'search', class: "btn btn-warning" %>
    <% end %>

这是我的控制器:

  def index
    @q = Rental.ransack(params[:q])
    @rentals = @q.result(distinct: true)
  end

我已经研究过这个问题,并且我不断看到人们在模型中添加一个洗劫者,就像我在这里所做的那样:

  ransacker :check_out_date, type: :date do
    Arel.sql('date(check_out_date)')
  end

我会这么说。我已经洗劫了其他工作。例如,我可以轻松地输入“标题”搜索字段,并且效果很好。但是,当我按日期搜索时,我仍然得到以下结果:

PG::UndefinedFunction: ERROR:  operator does not exist: date ~~* unknown
LINE 1: ...".* FROM "orders" WHERE "orders"."check_out_date" ILIKE '202...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

有人用简单的解决方案遇到过这个问题吗?

【问题讨论】:

  • 谢谢。这就是我的理解。我该怎么做呢?

标签: ruby-on-rails ruby postgresql ransack


【解决方案1】:

您的查询参数称为check_out_date_cont。最后的_cont 表示你想要check_out_date 列包含给定字符串的所有记录 - 这就是它使用ILIKE 运算符的原因,它根本不适用于日期。

您需要将其更改为 check_out_date_eq 才能正常工作。

参考:https://github.com/activerecord-hackery/ransack#search-matchers

【讨论】:

  • 那么还有比将日期存储为字符串更好的方法:) 但是,他在问题中表示:I simply want to search for orders with a specific date.
  • mea culpa 我倾向于忽略对手头的问题似乎多余的问题的某些部分
  • 我认为ransack gem 选择谓词名称_cont 不好,它实际上映射到arel 节点matches,在我看来,matches 更好。
  • @LamPhan _matches 已经存在,但您必须提供通配符,而 _cont 没有
猜你喜欢
  • 2012-09-18
  • 2021-08-10
  • 1970-01-01
  • 2022-07-13
  • 2016-11-17
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多