本文介绍了Postgres数组字段上的ActiveAdmin筛选器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ActiveAdmin中添加了以下过滤器。

I added the following filter in ActiveAdmin.

filter :roles, as: :select, collection Model::ROLES, multiple: true

但是当我选择过滤器值来搜索角色时。它给了我以下错误

but when i choose the filter value to search the roles. it gives me following error

PG::InvalidTextRepresentation: ERROR:  malformed array literal: "teacher"LINE 1: ...ted" = $1 AND roles" IN('teacher
DETAIL:  Array value must start with "{" or dimension information.                                                             ^

有什么想法吗?如何使用AA过滤器搜索/过滤ARRAY字段?我使用的是 Rails 4.2.4,
ruby​​ 2.2.2p95

Any idea ? How we can search/Filter ARRAY field using AA filters? I'm using Rails 4.2.4,ruby 2.2.2p95

推荐答案

我在这里提出了一个略有不同(并受其启发)的解决方案:

I came up to a solution slightly different (and inspired by) this one over here: https://stackoverflow.com/a/45728004/1170086

矿山涉及一些变化(并防止破碎包含运算符)。因此,您将基本上创建两个初始化文件:

Mine involves some changes (and prevent breaking contains operator in other cases). So, you're going to basically create two initializer files:

这一个用于Arel,为了支持 @> 运算符(PG中数组的包含运算符) n表列。

This one is for Arel, in order to support @> operator (array's contain operator in PG) for a given table column.

# config/initializers/arel.rb

module Arel
  class Nodes::ContainsArray < Arel::Nodes::Binary
    def operator
      :"@>"
    end
  end

  class Visitors::PostgreSQL
    private

    def visit_Arel_Nodes_ContainsArray(o, collector)
      infix_value o, collector, ' @> '
    end
  end

  module Predications
    def contains(other)
      Nodes::ContainsArray.new self, Nodes.build_quoted(other, self)
    end
  end
end

另一个文件旨在创建一个新的Ransack谓词,但我还决定支持:array 类型(Ransack本身不支持谓词)。

The other file aims to create a new Ransack predicate but I also decided to support the :array type (that's not natively supported in Ransack in terms of predicates).

# config/initializers/ransack.rb

module Ransack
  module Nodes
    class Value < Node
      alias_method :original_cast, :cast

      def cast(type)
        return Array(value) if type == :array
        original_cast(type)
      end
    end
  end
end

Ransack.configure do |config|
  config.add_predicate 'contains_array',
    arel_predicate: 'contains',
    formatter: proc { |v| "{#{v.join(',')}}" },
    validator: proc { |v| v.present? },
    type: :array
end

。您所需要做的就是:

And in other to use it. All you need to do is:

User.ransack(roles_contains_array: %i[admin manager])

或作为ActiveAdmin中的过滤器(我的情况):

Or as a filter in ActiveAdmin (which is my case):

ActiveAdmin.register User do
  # ...
  filter :roles_contains_array, as: :select, collection: User.roles_for_select
  # ...
end

我希望它对我有用。 ;)

I hope it works for you as it worked for me. ;)

这篇关于Postgres数组字段上的ActiveAdmin筛选器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:19