对存储在数组中的数据进行Ransack搜索(运算符不存在:整数 =整数)

我有一个Rails模型调用InfoData,它有一个名为error_codes的属性。 代码存储在类似[9,7,10,21](整数[])的数组中。

回顾一下

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

或者,您可以编写自己的了解PostgreSQL数组的ransacker 。 除非你做了很多这样的工作,否则这可能比你需要的更多的工作和复杂性。