Home:ALL Converter>How to search by exact hash in Rails ActiveRecord for JSON MySql field?

How to search by exact hash in Rails ActiveRecord for JSON MySql field?

Ask Time:2021-09-22T05:47:20         Author:Meliborn

Json Formatter

I have a field with json type in MySQL database. The field contains values like

{
    "city_eq": "NewYork",
    "rent_true": false,
    "estate_type_eq": 0
}

What is the proper way to search records by incoming hash? Like this:

Link.where(json_fields: {
    "city_eq": "NewYork",
    "rent_true": false,
    "estate_type_eq": 0
})

Query should return a record only if all values are the same and presented in field. Order of hash keys might differs.

Author:Meliborn,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275898/how-to-search-by-exact-hash-in-rails-activerecord-for-json-mysql-field
yy