Update single attribute in hash column
NomNomCameron opened this issue · comments
Currently use storext on jsonb columns on my models and just realized that when updating the hash column with certain values for keys I want to update, it destroys the rest of the hash (because you're essentially setting that column to equal the new hash you're passing in)
If it would be useful to the rest of the community here I'd be willing to open a pull request that enables the ability to update specific values for some keys while preserving the values of keys not passed in when updating the column storext is on.
I can also send an example if what I'm trying to achieve isn't clear.
@NomNomCameron this is interesting, and certainly, if possible, it should be done. The question is where.
First would be to find out if Postgres allows this. If it does, we should check if ActiveRecord::Store
already supports it. I think this kind of feature belongs there. What do you think?
As of this article (last updated: 2018-02-27) this should be possible:
irb(main):004:0> card.data["finished"] = true
=> true
irb(main):005:0> card.save
(0.2ms) BEGIN
SQL (0.9ms) UPDATE "cards" SET "data" = $1 WHERE "cards"."id" = $2 [["data", "{\"name\":\"Organize Kitchen\",\"tags\":[\"Fast\",\"Organize\",\"Carpet\",\"Cook\",\"Kitchen\"],\"finished\":true}"], ["id", 1]]
(6.6ms) COMMIT
=> true
having
create_table :cards do |t|
t.integer :board_id, null: false
t.jsonb :data
end
I quickly tested this (rails 5.2, ruby 2.5.1, storext 2.2.2) and it works as described in this article. So one can update a single value within the jsonb without destroying any other fields. However something like card.update!("data->>'foo'": 'bar')
raises UnknownAttributeError
.
If this answers the questions, we can close this issue? :)
Obviously I never took a look, or I forgot that I did. If you've worked on it I'd love to accept a PR