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

migrationのときにくせ者じゃ気をつけろ的なやつ2選

Posted at

マイグレーションのときに個人的にええっ?!てなったやつ2選(少なっ)ご紹介します
3選の予定でしたが眠気の都合上2選になりました

decimal型はデフォルトでは小数点以下0桁

映画レビューのテーブルとして、ratingには5.00満点として小数点以下が2桁入って欲しいとする

# migrationファイル
class CreateFilmsReviews < ActiveRecord::Migration[6.0]
  def change
    create_table :films_reviews do |t|
      t.string :title 
      t.decimal :rating
      t.text :comment
      t.integer :rating_user_id
      t.string :director
      t.integer :released 
      t.timestamps
    end
  end
end

mysqlでテーブル構造を確認

+----------------+---------------+------+-----+---------+----------------+
| Field          | Type          | Null | Key | Default | Extra          |
+----------------+---------------+------+-----+---------+----------------+
| id             | bigint(20)    | NO   | PRI | NULL    | auto_increment |
| title          | varchar(255)  | YES  |     | NULL    |                |
| rating         | decimal(10,0) | YES  |     | NULL    |                |
| comment        | text          | YES  |     | NULL    |                |
| rating_user_id | int(11)       | YES  |     | NULL    |                |
| director       | varchar(255)  | YES  |     | NULL    |                |
| released       | int(11)       | YES  |     | NULL    |                |
| created_at     | datetime(6)   | NO   |     | NULL    |                |
| updated_at     | datetime(6)   | NO   |     | NULL    |                |
+----------------+---------------+------+-----+---------+----------------+
9 rows in set (0.01 sec)

おやおやdecimal君、decimal(10,0)とはいかに
とりあえず適当にデータを入れてみる
土曜日に見たグリーンブック点数つけるとしたら4.05点

INSERT INTO films_reviews (
  title,
  rating,
  comment,
  rating_user_id,
  director,
  released,
  created_at,
  updated_at
) VALUES (
  'Green Book',
  4.05,
  'ほっこりする友情と黒人差別がメインテーマのロードムービー、見て良かった',
  1,
  'Peter Farrelly',
  2019,
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP
)

どれどれ、、、

mysql> SELECT rating FROM films_reviews;
+--------+
| rating |
+--------+
|      4 |
+--------+
1 row in set (0.00 sec)

テン05どこいった!
というわけでprecisionとscaleを指定しましょう。

class ChangeDataTypeFilmsReviewsOfRating < ActiveRecord::Migration[6.0]
  def up
    # precisionは全体の桁数、scaleは小数点以下の桁数
    change_column :films_reviews, :rating, :decimal, precision:3, scale: 2
  end

  def down
    change_column :films_reviews, :rating, :decimal
  end
end

データを入れ直す

mysql> SELECT rating FROM films_reviews;
+--------+
| rating |
+--------+
|   4.05 |
+--------+
1 row in set (0.00 sec)

小数点以下入りました!めでたし、めでたし

decimal型ではprecision, scaleをちゃんと書きましょう

複数インデックスの場合はインデックス名をつけましょう

ちょっと都合上さきほどのテーブルに映画の日本語タイトルを追加しました。

class AddColumnFilmsReviewsToJapaneseTitle < ActiveRecord::Migration[6.0]
  def change
    add_column :films_reviews, :japanese_title, :string
  end
end

複合インデックスを追加してみる

class AddCompositeIndexFilmsReviews < ActiveRecord::Migration[6.0]
  def change
    add_index :films_reviews, [:title, :japanese_title, :rating_user_id], unique: true
  end
end

rails db:migrateしてみる

rails aborted!
StandardError: An error has occurred, all later migrations canceled:

Index name 'index_films_reviews_on_title_and_japanese_title_and_rating_user_id' on table 'films_reviews' is too long; the limit is 64 characters

おおう、エラーが、、、
インデックスの名前は64文字までらしい

↓解決(インデックスの名前を指定)

class AddCompositeIndexFilmsReviews < ActiveRecord::Migration[6.0]
  def change
    add_index :films_reviews, [:title, :japanese_title, :rating_user_id], unique: true, name: 'each_title_user_rating_idx'
  end
end

複合インデックスは付け足し感が半端ないですが、以上です
グリーンブックはおすすめです。是非映画館で観て、観た後にケンタッキーを食べて、でも骨はちゃんとゴミ箱に捨ててください

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