LoginSignup
0
0

More than 5 years have passed since last update.

[Ruby]integer 型カラムの値を to_s する際は encoding を確認しよう(更新:しなくてもよさそう)

Last updated at Posted at 2018-09-21

※9/25:コメントを踏まえてタイトルを追記しました。とりあえずこの記事自体はこのまま残しておきます。

概要

例えばDBにこんな sample_model というテーブルがあったとします。

def change
  create_table :sample_model, id: :integer, unsigned: true, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4' do |t|
    t.string :name, null: false
    t.string :kind, null: false
    t.integer :sequence, default: 0, null: false
  end
end

そして、sample_model のレコードから取得した id を下記のように取得してみます。

SampleModel.find(some_pkey).id

このとき、id を文字列に変換すると、文字コードはなんと US-ASCII になります。

SampleModel.find(some_pkey).id.to_s.encoding
=> #<Encoding:US-ASCII>

string 型のカラムから値を取得した場合は UFT-8 になります。

SampleModel.find(some_pkey).kind.encoding
=> #<Encoding:UTF-8>

結論

今回の環境の場合、DB、テーブルではUTF8を使うように定義をしています。
対象のカラムが数値型であった場合でも、文字列に変換した場合に UTF-8 になることを期待していましたが
今回のように ASCII 文字になるケースがあることがわかりました。Ruby もしくは Active Record の仕様?なのかもしれません。みたいです。

あまりこういうケースも無さそうですが頭の片隅に置いておくと何かの役にたつかもしれません。

検証環境

  • Ruby 2.4.2p198 (2017-09-14 revision 59899) [x64-mingw32]
  • Rails 5.2.0
  • MySQL 5.6.31
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0