Ruby on Rails UTF8 issue

2019-08-04 12:42发布

When I run my code:

@a = People.order('created_at DESC').limit(1).pluck(:name)

it returns me this:

"\xD0\x9A\xD0\xB0\xD1\x81\xD0\xBB"

I read that it's UTF8 issue. For solve this problem I did:

  1. My MySQL table is in UTF8 utf8_general_ci
  2. In application.rb I paste:

    class Application < Rails::Application
        config.encoding = "utf-8"
    

but all these steps did not help me. In MySQL table all looks correctly and this issue just with the Russian letters.

Any ideas how to solve this problem?

2条回答
在下西门庆
2楼-- · 2019-08-04 13:25

Actually, the string value seems to be correct, if you decode it there will be "Касл". So I believe it should work well once you output it into the HTML view.

At the same time, something is probably wrong with your console. Try to run puts __ENCODING__ in the console, if it doesn't return the UTF-8 then something is misconfigured with the IRB.

查看更多
不美不萌又怎样
3楼-- · 2019-08-04 13:28

"\xD0\x9A\xD0\xB0\xD1\x81\xD0\xBB" is an ASCII-8BIT string encoded.

It maybe the problem of your console try to display this text. Rails may still render it correctly in view. If not, you can convert it to utf-8 by using .force_encoding("UTF-8"):

"\xD0\x9A\xD0\xB0\xD1\x81\xD0\xBB".force_encoding("UTF-8")
# => "Касл"
查看更多
登录 后发表回答