Searching serialized fields in Rails
Model
serialize :item_ids, Array scope :including_all_id, -> (arr) { where( arr.map { |id| "(item_ids LIKE '% #{id}\n%')" }.join(" AND ") )} scope :including_any_id, -> (arr) { where( arr.map { |id| "(item_ids LIKE '% #{id}\n%')" }.join(" OR ") )} # Serialized item_ids (eg [11, 12, 13]) stored in database in particular fashion: "11\n 12\n 13\n" hence query would be '% #{id}\n%'
In use
Post.including_all_id(['11', '13']) Post.including_any_id(['1', '11', '99'])
Hash: https://nandovieira.com/using-postgresql-and-hstore-with-rails