我有一个名为 InfoData 的 Rails 模型,它有一个名为 error_codes 的属性。代码存储在数组中,如 [9,7,10,21] (integer[]) .
回顾一下
InfoData.first.error_codes
=> [9,7,5]
我尝试对其使用 ransack 来搜索是否存在特定代码(通过选择选项)。对于 error_codes_in (_in ransack 谓词),我收到以下错误
operator does not exist: integer[] = integer
LINE 1: ...ranch_id" WHERE "info_data"."error_codes" IN (9) A...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
应该如何解决?
最佳答案
我认为最简单的方法是向模型添加一个范围并告诉 Ransack 它可以使用该范围。您的模型中类似这样的内容:
class InfoData < ApplicationRecord
def self.error_codes_has(code)
# Or use `scope` to define this class method if you prefer
# doing it that way.
where(':code = any(info_datas.error_codes)', code: code)
end
def self.ransackable_scopes(auth = nil)
%i[error_codes_has]
end
end
然后在搜索表单中使用该范围:
<%= search_form_for @q do |f| %>
...
<%= f.label :error_codes_has %>
<%= f.search_field :error_codes_has %>
...
<% end %>
或者,您可以 write your own ransacker理解 PostgreSQL 数组。除非您做很多这样的事情,否则这可能比您需要的更多工作和复杂性。
关于sql - 对数组中存储的数据进行搜查(运算符不存在 : integer[] = integer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340638/