Expose a simple set of methods to allow fast atomic updates of json
/jsonb
columns of ActiveRecord models using PostgresQL jsonb_set
function
- Support updates of
json
andjsonb
columns - Support update of deeply nested fields
- Support update of multiple fields at once
Add this line to your application's Gemfile:
gem 'atomic_json'
And then execute:
$ bundle install
To update a json
or jsonb
column, simply pass a Hash to the bellow method call,
using the column name as top level key and a nested hash of the value(s) you're willing to update
Only the fields you've specified will be updated
order.data
=> { amount: 50.00, first_name: 'Milkpie', last_name: 'Starlord' }
order.json_update(data: { amount: 10.00 })
order.data
=> { amount: 10.00, first_name: 'Milkpie', last_name: 'Starlord' }
For the sake of simplicity, AtomicJson mimic the behavior of standard ActiveRecord query methods to update database fields
Same as ActiveRecord update_columns
, this method will make a straight database update
- Validations are skipped
- Callbacks are skipped
updated_at
is not updated
order.json_update_columns(data: { paid: false })
=> true
Same as ActiveRecord update
, this method will
- Invoke validations
- Invoke callbacks
- Touch record
updated_at
order.json_update(data: { paid: false, product_id: 3772389212 })
=> false
Same as the above json_update!
, but will raise an ActiveRecord::RecordInvalid
exception
if a custom validation fails
order.json_update!(data: { paid: false, product_id: 3772389212 })
=> ActiveRecord::RecordInvalid Exception: Validation failed: data product_id can't be changed
- Support update of
json
/jsonb
arrays via index and key/value id
- PostgresQL version 9.5 minimum
The gem is available as open source under the terms of the MIT License.