Multibyte characters in JSON are lost when stored in the database

I convert my hash to JSON using the Rails.to_json () method.

Hash:

{ "Größe" => "XL" } 

JSON:

 "{\"Gr\\u00f6\\u00dfe\":\"XL\"}" 

After that, the JSON string is stored in the hstore (Postgres) column called static using this Rails (3.2.6) SQL command:

 UPDATE ... "static" = 'options=>"{\"Gr\u00f6\u00dfe\":\"XL\"}"' WHERE ... 

One backslash occurred.

In the database itself, the static column looks like this:

 "options"=>"{\"Gru00f6u00dfe\":\"XL\"}" 

All backslashes for u00f6 and u00dfe have disappeared.

JSON.parse () no longer identifies multibyte characters, so it returns the following hash:

 { "Gru00f6u00dfe" => "XL" } 

Does anyone know how to prevent this? Thanks for any help!

+4
source share
1 answer

Out of the box, rails do not support PostgreSQL hstore. But the fix is ​​easy, just use activerecord-postgres-hstore gem. Using activerecord-postgres-hstore free you from serialization or coding issues. that's how

1) Set the gem and then change the static column type to hstore

 class ChangeHStoreDateTypeInMyTable < ActiveRecord::Migration def change change_column :my_table, :static, :hstore end 

2) Add index

 CREATE INDEX my_table_gin_static ON my_table USING GIN(static); 

3) Now you can create an instance of the model object and update the values, as usual, without worrying about serialization or coding.

 @model.static["Größe"] = "XL" 

Additional information: https://github.com/softa/activerecord-postgres-hstore

0
source

Source: https://habr.com/ru/post/1433279/


All Articles