TAGS :Viewed: 13 - Published at: a few seconds ago

[ Use ransack to find objects whose array attribute contain a specific string ]

Model A has attribute "languages", which is an array contains element such as "English", "French". My site has a form which allows user to select a language and it will display all object whose "languages" includes that language.

How to design my controller and view to do that? From the docs, there are ways to check if an element is in a query array, not the other way round.

Answer 1


I just answered this on another question, I will add the answer here too for future reference.

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.