Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only part of json, stored in Postgres, with ActiveRecord

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?

like image 841
Alexander Popov Avatar asked Feb 10 '16 11:02

Alexander Popov


1 Answers

Try User.select("settings -> 'language' as user_language"). Each object in the resulting relation should respond to user_language.

like image 75
Dani Avatar answered Oct 12 '22 09:10

Dani