-->

Ransack search string arrays stored in db

2019-07-20 19:20发布

问题:

I'm trying to search using ransack for articles.

In one of my question in how to get the articles based on their tags, I found out how to do so:

Find articles where array

Now I just want to do the search with ransack but I get an error

I have it like this

<%= search_form_for @q do |f| %>
        <div class="row">
          <div class="col-md-2">
            <%= f.label :tags_in %> <span data-toggle='tooltip', data-placement='right', title='Una o dos palabras máximo para expecificar lo que está buscando' class="glyphicon glyphicon-question-sign" ></span>
            <%= f.search_field :tags_in, class: 'form-control' %>
          </div>
          <div class="col-md-2">
            <%= f.submit 'Buscar', class: 'btn btn-primary m-t-large' %>
          </div>
        </div>

      <% end %>

the error I get when performing this searching for xbox is the following:

PG::InvalidTextRepresentation: ERROR:  array value must start with "{" or dimension information
LINE 1: ...es".* FROM "articles" WHERE "articles"."tags" IN ('xbox')  O...

heres the controller:

def index
    @q = Article.ransack(params[:q])
    @articles = @q.result.paginate(page: params[:page], :per_page => 10).order('created_at DESC')
  end

How can I search for the articles using their tags?

Thanks!

回答1:

As discussed on this issue you need to add the gem postgres_ext to your project:

# Gemfile
gem 'postgres_ext'

And add this to an initializer:

# config/initializers/ransack.rb
Ransack.configure do |config|
  %w[
    contained_within
    contained_within_or_equals
    contains
    contains_or_equals
    overlap
  ].each do |p|
    config.add_predicate p, arel_predicate: p, wants_array: true
  end
end

After that you'll be able to use contains in a serialized array.