LoginSignup
29
23

More than 5 years have passed since last update.

Rails migration decimalカラムをデフォルトで作成すると小数点以下が0桁になるから気をつけよう

Last updated at Posted at 2017-08-05

decimalをデフォルトで作成すると小数点以下が入力できない

例えば重さを保存するカラムを作る場合はmigrationファイルにこんな感じで書きますよね?

class CreateHoges < ActiveRecord::Migration[5.1]
  def change
    create_table :hoges do |t|
      t.decimal :weight
    end
  end
end

しかし、設定値なしでdecimalカラムを作成する場合

`weight` decimal(10,0) DEFAULT NULL

で作成されてしまうんです。

面倒臭がらずに許容桁数を指定しましょう

桁数の指定optionは以下の通りです。

option value
precision 全体の桁数
scale 小数点以下の桁数

以下のように書いた場合は全体で6桁、小数点以下2桁です。

class CreateHoges < ActiveRecord::Migration[5.1]
  def change
    create_table :hoges do |t|
      t.decimal :weight, precision: 6, scale: 2
    end
  end
end

注意点

  • precisionは全体の桁数です。
  • precisionは整数の桁数ではないです。
29
23
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
29
23