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.
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.