使用Ransack搜索关联中的字符串数组失败

时间:2015-11-28 05:52:22

标签: ruby-on-rails arrays ransack

我想我可能已经知道了答案,但我希望可能有其他解决办法。

我有User模型与has_many关联到另一个模型Enrollment,其中包含字符串数组roles

我正在尝试对角色进行Ransack搜索,例如:

:enrollments_roles_cont 'guest'

无论我使用哪种运营商,搜索都会失败:

CONT:

PG::UndefinedFunction: ERROR:  operator does not exist: text[] ~~* unknown
LINE 1: ..." IS NULL AND ("enrollments_public_users"."roles" ILIKE '%ma...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

EQ:

PG::InvalidTextRepresentation: ERROR:  malformed array literal: "manager"
LINE 1: ... IS NULL AND "enrollments_public_users"."roles" = 'manager' ...
                                                             ^
DETAIL:  Array value must start with "{" or dimension information.

我猜这个失败是因为我的阵列'列实际上是一个字符串。所以有两个问题。

  1. 将其切换为数组类型会修复此问题吗?
  2. 我能以另一种方式解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

它不漂亮,但它有效:

在我的Enrollments模型中:

ransacker :roles do
  Arel.sql("array_to_string(roles, ',')")
end
相关问题