我有一个名为 InfoData 的 Rails 模型,它有一个名为 error_codes 的属性。代码存储在数组中,如 [9,7,10,21] (integer[])
。
回顾一下
InfoData.first.error_codes
=> [9,7,5]
我尝试对其使用 ransack 来搜索是否存在特定代码(通过选择选项)。对于 error_codes_in (_in ransack predicate) 我收到以下错误
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 %>
或者,你可以编写你自己的掠夺者 https://github.com/activerecord-hackery/ransack/wiki/Using-Ransackers理解 PostgreSQL 数组。除非您做很多这样的事情,否则这可能比您需要的工作量和复杂性更多。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)