1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails の binary型 を MySQL で使用した際のトラブルシューティング

Last updated at Posted at 2019-02-21

概要

PDFや画像をアップロード・ダウンロードする機能を実装し、開発環境(SQLite)では動作しているものを本番環境(MySQL)にデプロイした際のトラブルシューティングです。

トラブルとしては以下の2つのトラブルに遭遇しました。

  • MySQL でクライアントからサーバに送出できるパケットの制限を超えた
  • Railsのbinaly型はMySQLではBLOB型となるが、容量不足だった

環境(開発・本番)

# 開発環境
$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
$ rails -v
Rails 5.1.6
$ gem list sqlite
sqlite3 (1.4.0, 1.3.13)

# 本番環境
$ ruby -v
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux]
$ rails -v
Rails 5.1.6
$ mysql --version
mysql  Ver 14.14 Distrib 5.7.25, for Linux (x86_64) using  EditLine wrapper

max_allowed_packetを変更する

本番環境にデプロイしてファイルをアップロードしてみると例外が発生してしまいました。ログを見てみると以下のようなエラーメッセージでした。

Mysql2::Error: MySQL client is not connected: ROLLBACK

Mysql2::Error: MySQL client is not connected: ROLLBACKを解消した話
mysql max_allowed_packetを変更する

この辺の情報を参考にしましたが、私の場合はconfファイルを変更してMySQLの再起動で解消しました。

$ sudo vi /etc/my.cnf
my.cnf
[mysqld]
max_allowed_packet=16MB
$ sudo systemctl restart mysqld.service

該当フィールドをmediumblobに変更する

次に遭遇したエラーメッセージは以下になります。

Data too long for column 'upload_file'

[【Rails×MySQL】保存できる画像ファイルの容量を変更する]
(https://qiita.com/residenti/items/d791533423d3f4999a61)
【Rails・MySQL】MySQLのデータ型とRailsのマイグレーションファイルのデータ定義の対応まとめ

こちらを参考に、カラム修正のマイグレーションを行う事で解消しました。

migration.rb
class ChangeUploadFileToDocument < ActiveRecord::Migration[5.1]
  def change
    change_column :documents, :upload_file, :binary, :limit => 5.megabyte
  end
end
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?