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?
.map(&:attributes)on the result.attributesreturns this{"id"=>nil, "?column?"=>"English"}. What confused me is the fact that normally the object would look like this when selecting a normal (not json) attribute:#<User:0x007f38200f3598 id: nil, name: "John">. However, apparently json selected data doesn't work like that.#to_sthat's defined in a way that only outputs known columns. Custom columns fromselectare not known to be inside the table, so they're not printed out in#to_s, but are mapped regardless.