【问题标题】:Ransack search on data stored in array (operator does not exist: integer[] = integer)Ransack 搜索存储在数组中的数据(运算符不存在:整数 [] = 整数)
【发布时间】:2018-03-17 18:48:40
【问题描述】:

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

应该如何解决?

【问题讨论】:

    标签: sql ruby-on-rails ruby activerecord ransack


    【解决方案1】:

    我认为最简单的方法是为您的模型添加一个范围,并告诉 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 数组。除非你做很多这样的事情,否则这可能比你需要的更多的工作和复杂性。

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2015-09-24
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多