Search code examples
ruby-on-railsrubyransack

Search an array of values with Ransack


I'm new to Ransack and I've ran into what appears to be a case that isn't cleanly covered by Ransack. I'm basically trying to search a value but the searched value is wrapped in an array.

CODE:

<%= f.search_field :category_or_account_number_or_status_or_account_number_or_account_name_or_accounts_name_or_accounts_number_or_user_name_or_user_rep_code_list_cont_any %>

At the very end there is this piece user_rep_code_list_cont that is a default array attribute on users it looks like this currently ["al20", "b234"]

So, when I type al20 in the Ransack search bar I get this error.

ERROR:

PG::UndefinedFunction: ERROR:  operator does not exist: character 
varying[] ~~* unknown
LINE 1: ..."name" ILIKE '%al20%') OR "users"."rep_code_list" ILIKE 
'%al...
                                                         ^
HINT:  No operator matches the given name and argument type(s). You 
might need to add explicit type casts.

CONTROLLER:

def index
  @q = Submission.submissions_for(user: current_user).ransack(params[:q])
  @submissions = @q.result.includes(:user, :accounts).ordered(current_user).page(params[:page]).per(25)
end

Again, I'm not a Ransack expert but this seems like something that should be covered by now. I want to search an attribute on a model that is an Array.


Solution

  • I ended up using a custom Ransacker for this case:

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

    This will turn the array into a string so that Ransack can search with the cont predicate. Not sure if this is the best way to do it but it worked for my case.