Say I have a model User, which has a field of type json called settings. Let's assume that this field looks roughly like this:
{
  color: 'red', 
  language: 'English', 
  subitems: 
    {
      item1: true, 
      item2: 43, 
      item3: ['foo', 'bar', 'baz']
    }
}
If I do User.select(:settings) I will get all the settings for each user. But I want to get only the languages for a user. I tried both:
User.select("settings -> 'language'")
and
User.select("settings ->> 'language'")
but this just returns empty objects:
[#<User:0x007f381fa92208 id: nil>,
...]
Is this at all possible? If yes - can I do it using just json or do I need to switch to jsonb?
Try User.select("settings -> 'language' as user_language").
Each object in the resulting relation should respond to user_language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With