activerecord-postgres-hstore
activerecord-postgres-hstore copied to clipboard
Update always sets hstore column
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.
I'll take a look at this during this week
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:
-
hstore
columns are always updated or - 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).
Even if you don't change anything in hstore column, #save issue UPDATE ..... How to fix the bug?
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.
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?