sql - 对数组中存储的数据进行搜查(运算符不存在 : integer[] = integer)

标签 sql ruby-on-rails ruby activerecord ransack

我有一个名为 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/

相关文章:

sql - 在 Entity Framework 中使用正则表达式进行搜索

SQL 其中连接集必须包含所有值但可能包含更多

ruby-on-rails - Rails 创建一个新对象而不是更新它

ruby-on-rails - 如何将 curl 中的 POST 请求转换为 ruby​​?

ruby-on-rails - Rails 遍历深度哈希数组

sql - 如何确定按位值中的最大位

mysql - 尝试使用mysql在第一个字母上以大写开头的单词

ruby-on-rails - 类名不在模块中定义,除非它在代码中使用

ruby-on-rails - 在 Ruby 中以编程方式访问属性/方法注释

Ruby:在倒排索引中搜索部分匹配