Ruby on Rails UTF8 issue

2019-08-04 13:23发布

问题:

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?

回答1:

"\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")
# => "Касл"


回答2:

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.