1

This is a follow up question to this one:

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']
    }
}

The difference to the question cited above is that I'd like to know how to exclude part of the json. So here, I want to select everything from settings except:

subitems: 
  {
    item1: true, 
    item2: 43, 
    item3: ['foo', 'bar', 'baz']
  }
4
  • Much more complex than the related question :] Would a solution using two queries suite you? First query to get all top level json keys, second query to actually select all fields expect for the ones you wish to exclude. Commented Feb 10, 2016 at 13:33
  • Well, actually, I wouldn't mind just selecting all the keys, that I need manually. So I would need something like: User.select("settings -> ['color', 'language'] AS modified_settings"), which should return objects, that respond to the method modified_settings, which should return {color: 'red', language: 'English'}. Do you know how to select multiple keys at once? Commented Feb 10, 2016 at 13:41
  • 1
    Unfortunately I could find a way to retrieve multiple keys at once either. But you can always construct you query dynamically with something like keys_to_fetch.map{ |k| "setting -> '#{k}' as setting_#{k}"}.join(',') Commented Feb 10, 2016 at 13:44
  • Yes, thank you. I think this is a good workaround! Commented Feb 10, 2016 at 13:45

1 Answer 1

2

in my case,
>>User.select("subitem -> 'item1' AS subitem1", "subitem->'item2' AS subitem2").map(&:attributes)

with rails 5

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.