Skip to content
This repository has been archived by the owner on Jun 11, 2022. It is now read-only.

Update single attribute in hash column #45

Open
NomNomCameron opened this issue Nov 26, 2017 · 4 comments
Open

Update single attribute in hash column #45

NomNomCameron opened this issue Nov 26, 2017 · 4 comments

Comments

@NomNomCameron
Copy link

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.

@ramontayag
Copy link
Contributor

ramontayag commented Nov 26, 2017

@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?

@swiknaba
Copy link

swiknaba commented Sep 26, 2018

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? :)

@ramontayag
Copy link
Contributor

ramontayag commented Sep 27, 2018 via email

@ramontayag
Copy link
Contributor

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants