随机搜索存储在数组中的数据(运算符不存在:integer [] =整数) [英] Ransack search on data stored in array (operator does not exist: integer[] = integer)

查看:80
本文介绍了随机搜索存储在数组中的数据(运算符不存在:integer [] =整数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Rails model call InfoData and it has an attribute called error_codes. The codes are stored in an array like so [9,7,10,21] (integer[]) .

回顾一下

InfoData.first.error_codes 
=> [9,7,5]

我尝试在上面使用ransack来搜索特定的代码存在(通过选择选项)。对于error_codes_in(_in ransack谓词),我收到以下错误

I try to use ransack on it in order to search if a specific code is present(via a select option). For error_codes_in (_in ransack predicate) I receive the following error

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它可以使用该范围。在您的模型中是这样的:

I think the easiest way would be to add a scope to your model and tell Ransack that it can use that scope. Something like this in your model:

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

然后在搜索表单中使用该范围:

And then use that scope in your search form:

<%= search_form_for @q do |f| %>
  ...
  <%= f.label :error_codes_has %>
  <%= f.search_field :error_codes_has %>
  ...
<% end %>

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

Alternatively, you could write your own ransacker that understands PostgreSQL arrays. That's probably more work and complexity than you need unless you're doing a lot of this.

这篇关于随机搜索存储在数组中的数据(运算符不存在:integer [] =整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆