Find and update a collection in JSONB

255 Views Asked by At

I have a Rails 5.0 app with a JSONB column called data, which contains an array of hashes:

[
    {'event': 'web_session', 'user_id': 1, 'count': 13},
    {'event': 'web_session', 'user_id': 2, 'count': 10},
    {'event': 'web_session', 'user_id': 3, 'count': 42}
]

How would I update one of the hashes, e.g. matching 'user_id': 2, with a different count value?

Is this the most efficient way (I'd potentially have ~1 million hashes):

h = data.find {|h| h['user_id'] == 2}
h['count'] = 43
save
0

There are 0 best solutions below