Dan Tappin
Dan Tappin

Reputation: 3032

Searching a string array in an association fails with Ransack

I think I may know the answer already but I was hoping that there may be alternate solution.

I have a User model with has_many association to another model Enrollment with a string array roles.

I am trying to run a Ransack search on the roles for example:

:enrollments_roles_cont 'guest'

No matter which operator I use the search fails:

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.

I am guessing this fails because my 'array' column is actually a string. So two questions.

  1. Would switching that to an array type fix this?
  2. Can I fix this another way?

Upvotes: 1

Views: 554

Answers (1)

Dan Tappin
Dan Tappin

Reputation: 3032

It's not pretty but it works:

In my Enrollments model:

ransacker :roles do
  Arel.sql("array_to_string(roles, ',')")
end

Upvotes: 2

Related Questions