Skip to content

Instantly share code, notes, and snippets.

@r11n
Last active May 11, 2020 05:59
Show Gist options
  • Save r11n/0a9f800834a62d235461e080f7cc2eae to your computer and use it in GitHub Desktop.
Save r11n/0a9f800834a62d235461e080f7cc2eae to your computer and use it in GitHub Desktop.
Querying Postgres JSONB arrays using Active Record in Raiils
class ApplicationRecord < ActiveRecord::Base
extend JsonQuerying
self.abstract_class = true
end
# include the following module in ApplicationRecord or any any model you wish use it in
module JsonQuerying
# method for checking if given array equals the value in DB.
def array_eq(column_name, *args)
array_contains(column_name, *args)
end
# method for checking if array contains all the values.
def array_contains(column_name, *args)
args = args.map(&:to_s) unless [Integer, Float].include?(args[0].class)
where(["#{table_name}.#{column_name} ?& ARRAY[:vals]", { vals: args }])
end
# method for checking if array contains any of the values.
def array_contains_any(column_name, *args)
args = args.map(&:to_s) unless [Integer, Float].include?(args[0].class)
where(["#{table_name}.#{column_name} ?| ARRAY[:vals]", { vals: args }])
end
class SomeModel < ApplicationRecord
end
# for finding records containing any of the elements in array
SomeModel.array_contains_any(:column_a, ['x', 'y', 'z'])
# for finding records containing any of the all the elements in array
SomeModel.array_contains(:column_a, ['x', 'y', 'z'])
# or
SomeModel.array_eq(:column_a, ['x', 'y', 'z'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment