Last active
May 11, 2020 05:59
-
-
Save r11n/0a9f800834a62d235461e080f7cc2eae to your computer and use it in GitHub Desktop.
Querying Postgres JSONB arrays using Active Record in Raiils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationRecord < ActiveRecord::Base | |
extend JsonQuerying | |
self.abstract_class = true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeModel < ApplicationRecord | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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