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

邮差的信 提交于 2020-01-01 10:08:33

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/35313997/how-to-select-only-part-of-json-stored-in-postgres-with-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!