在 Rails 中,Ransack 搜索在尝试按 ID 过滤时给出错误“PG::UndefinedFunction: ERROR: operator does not exist”

THp*_*ubs 2 ruby-on-rails ransack ruby-on-rails-4

我试图通过ID. 这是我的搜索表单:

<%= search_form_for @search, url: dash_orders_path, id: 'searchForm' do |f| %>
    <div class="col-md-4 margin-top-15">
        <%= f.search_field :id_cont, class: 'form-control', placeholder: 'Order id' %>
    </div>
    <span class="button-sec pull-left width-wide center-text searchBtn">
        <%= f.submit "Search", class: "button-big blue" %>
        <%= f.submit "Clear", class: "button-big red", onclick: "$('#searchForm')[0].reset();" %>
    </span>
<% end %>
Run Code Online (Sandbox Code Playgroud)

尝试进行搜索时,会出现如下错误:

PG::UndefinedFunction: ERROR:  operator does not exist: integer ~~* integer
LINE 1: ...CT  "orders".* FROM "orders" WHERE ("orders"."id" ILIKE 0)  ...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT  "orders".* FROM "orders" WHERE ("orders"."id" ILIKE 0)  ORDER BY "orders"."updated_at" DESC LIMIT 2 OFFSET 0
Run Code Online (Sandbox Code Playgroud)

可能是什么问题?

小智 5

我遇到了类似的问题,并发现您的帖子试图找到解决方案。这就是我解决它的方法:

问题是 PG 试图将整数(在我的例子中是日期)与字符串匹配。

我将谓词更改为 _eq ,一切都很完美。

使用 :field_cont (contains) 谓词,Ransack 在 PG 中进行的 SQL 查询是 ILIKE,使用 :field_eq 是 IS (=)。

我想现在来帮助你已经太晚了,但也许其他人可以从这个答案中受益。

祝你好运,


die*_*ky1 5

让您继续使用您的 id 与 ransack 的 cont 谓词。将此添加到您的订单模型中:

ransacker :id do
  Arel.sql("to_char(\"#{table_name}\".\"id\", '99999')")
end
Run Code Online (Sandbox Code Playgroud)

ransacker 方法允许您执行自定义搜索,在这种情况下,正如这个ransacker wiki所说,ransacker 方法可以避免输入中的歧义,如果您使用 MySQL,则存在不同的情况。

希望这可以帮助。