activerecord-postgres-hstore after save error ordering in Hash

拟墨画扇 提交于 2019-12-14 03:56:59

问题


store as Hash Table with Hstore, wrong ordering in Hash after Save

class Service < ActiveRecord::Base
  serialize :properties, ActiveRecord::Coders::Hstore
end

service = Service.new
service.properties = { "aaa" => 1, "zz" => 2, "cc" => 3, "d" => 4 }
#=> { "aaa" => 1, "zz" => 2, "cc" => 3, "d" => 4 }
service.save
reload!
service = Service.find(:id)
service.properties
#=> { "d" => "4", "cc" => "3", "zz" => 2, "aaa" => 1 }
Bug::: wrong ordering after save

Is it because after serialize that it orders by Tree. Any ideas or anyone had faced this problem before? Thanks in advance.


回答1:


From the fine PostgreSQL manual:

F.16. hstore
[...]
This module implements the hstore data type for storing sets of key/value pairs within a single PostgreSQL value.
[...]
The order of the pairs is not significant (and may not be reproduced on output).

So PostgreSQL's hstore type is an unordered set of key/value pairs that doesn't guarantee any particular order of the key/value pairs. Once your Ruby Hash is converted to an hstore, the ordering is lost.

If you need to maintain the order in your Hash you'll have to use a different serialize format.



来源:https://stackoverflow.com/questions/14888580/activerecord-postgres-hstore-after-save-error-ordering-in-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!