i have the same problem described in this question. PostgreSQL: compare jsons
but, i want a way to do it in rails, i have metadata column, that i have to query every time a record inserted. so, i have to compare between the value that will be inserted and the content i have, also, that column maybe empty.
what i have tried to use the json::text
, but that means that i have to make a query for each setting of the json keys and values.
## for checking the empty query and if not empty, i loop through the json objects
if metadata.to_s == '{}' || metadata.to_s == ''
gears = gear_query.where("metadata::text = ?", metadata.to_s)
else
gears = gear_query.each.collect{ |g| g if g.eq_metadata?(metadata) }.compact
end
## looping through all the shapes of the json objects
## and calling diff function to recognize if the objects are different or not
def eq_metadata?(metadata)
src_mtd = self.metadata.sort_by { |k, v| k }.to_h
new_mtd = metadata.sort_by { |k, v| k }.to_h
src_keys = src_mtd.keys.each.map(&:to_sym)
new_keys = new_mtd.keys.each.map(&:to_sym)
((src_keys == new_keys) && (src_mtd.values == new_mtd.values))
end
i think that there is a better way, or that i am missing something with my code. my question not about raw sql queries, it is about a way to compare json objects' content stored in the database with a json object in hand. the way i took is to get all the json objects out of the database then comparing them to the json object in hand... is there another way??