How to select only json part stored in Postgres using ActiveRecord

Say I have a User model that has a json type field called settings . Suppose this field looks something 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 languages โ€‹โ€‹for the user. I tried both:

 User.select("settings -> 'language'") 

and

 User.select("settings ->> 'language'") 

but this just returns empty objects:

 [#<User:0x007f381fa92208 id: nil>, ...] 

Is it possible? If so - can I do this using only json or do I need to switch to jsonb ?

+5
source share
1 answer

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

+6
source

Source: https://habr.com/ru/post/1242698/


All Articles