2

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was trying to use Hstore to store custom header/values for a csv I was creating. However after reading this I decided to store them in 2 separate arrays instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.