Search code examples
sqlruby-on-railsrubyjsonb

How to find key of hash in jsonb in Rails?


Example Model Home, column: animals. Inside animals jsonb like this:

dogs: {
  dog1: { attributes...},
  dog2: { attributes...},
  ...
}

Question
How can I find dog1 only by the key("dog1")


Solution

  • This is not supported by Active Record natively. You'll have to write some custom where clauses. For example in Postgres, see documentation here: https://www.postgresql.org/docs/9.4/functions-json.html.

    Some examples are listed here: https://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails, under the "Querying your jsonb column" section!

    # preferences->twitter OR preferences->github
    User.where('preferences ?| array[:keys]', keys: ['twitter', 'github'])