activerecord-postgres-hstore icon indicating copy to clipboard operation
activerecord-postgres-hstore copied to clipboard

Update always sets hstore column

Open izoomi opened this issue 11 years ago • 5 comments

When I update other fields, the hstore column, is always set as well.

post = Post.create(title: 'Title')
post.update_attribute(:title, 'Title2')
# (0.2ms)  BEGIN
# (0.4ms)  UPDATE "posts" SET "title" = 'Title2', "updated_at" = '2013-05-03 16:01:43.841376', 
# "options" = '' WHERE "posts"."id" = 6100
# (1.6ms)  COMMIT
# => true

The options column gets updated as well.

izoomi avatar May 03 '13 16:05 izoomi

I'll take a look at this during this week

diogob avatar May 06 '13 14:05 diogob

Rails core is dealing with the flip side of this issue: https://github.com/rails/rails/issues/6127

The problem is that if options already has some stuff in it, and you update a single key within it, you want post.save to update the options column, too.

Rails's change tracking doesn't work at the granularity of keys within a hash, so it's either:

  1. hstore columns are always updated or
  2. only when the entire attribute is assigned

In the latter case, a partial update won't be saved unless the developer is careful (actually reassigning the attribute or calling #options_will_change! everywhere a partial update occurs).

sjmadsen avatar May 07 '13 16:05 sjmadsen

Even if you don't change anything in hstore column, #save issue UPDATE ..... How to fix the bug?

edbond avatar Apr 14 '14 11:04 edbond

I've ended up with moving hstore column to separate relation. So now if need to access hstore attributes, will call them directly, by product.attrs.data instead of product.attrs.

Before:

class Product
  serialize :attrs, ActiveRecord::Coders::Hstore
end

After:

class Product
  has_one :attrs, class_name: 'ProductAttrs'
end
class ProductAttrs
  belongs_to :product
  serialize :data, ActiveRecord::Coders::Hstore
end

It's not so efficient on selects, but I do many more updates, than selects, so it works for me.

staszek-arsdata avatar Jun 11 '14 10:06 staszek-arsdata

Has there been any update on this? I've run into an issue where hstore is removing columns in my shared pg database when a different api does an update request. The columns aren't defined in one api but are defined in the other, shouldn't those columns remain concrete and not be removed from the table?

OctoberComstock avatar Jan 25 '18 01:01 OctoberComstock