I have a hstore field called extra_info with key is 'real_params' and value is a hash . In database this pair is like "real_params"=>"{\"master\":\"13\",\"reference_month\":\"58\",\"distributor\":\"14\"}"
.
Seeking through rails console with Storage.where("extra_info -> 'params' = '{\"master\":\"13\",\"reference_month\":\"58\",\"distributor\":\"14\"}'")
returns nothing, but changing the params order to Storage.where("extra_info -> 'params' = '{\"master\":\"13\",\"distributor\":\"14\",\"reference_month\":\"58\"}'")
i find it.
Why order is not the same? Why this is happining?
The hstore column type is for storing key/value pairs where both the key and value are strings (at least until PostgreSQL 9.4). The value in your hstore appears to be the JSON representation of a Hash but that's still just a string. These two:
'{"master":"13","reference_month":"58","distributor":"14"}'
'{"master":"13","distributor":"14","reference_month":"58"}'
are different strings even though they're equivalent Hashes once you parse the JSON.
You'll probably have a better time if you can switch to a JSON column instead of hstore. Then use the #>
operator to look at the paths into the JSON that you care about.
If you must stay with hstore then you need to use a fixed key order in your Hashes (make sure they're always in alphabetical order for example) and hope that JSON will preserve the key order. You'll have to rebuild all your hstore values before they get to the database (probably using a before_validation
hook) and might mean rebuilding your whole hstore column.