LoginSignup
18
13

More than 5 years have passed since last update.

Rails g modelの際のdecimal型のフィールドについての注意点

Posted at

例えば10進数で最大桁数10桁、小数点以下2桁のpriceフィールドを持ったモデルを作成するとする。

このときシングルクォーツで囲ってやらないとヤヴァイ。

rails g model product 'price:decimal{10,2}'

理由は以下に書いてあるのですが、

要は囲わないとマイグレーションファイルがこのようになっちゃう。

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.decimal10 :price
      t.decimal2 :price

      t.timestamps
    end
  end
end

decimal10型とdecimal2型のpriceができちゃう。

bash上でこうやってチェックしてみるとわかりやすい。

$ echo p{1,2}
p1 p2

なのでシングルクォーツで囲って

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.decimal :price, precision: 10, scale: 2

      t.timestamps
    end
  end
end

このように生成するということです。

その他参考記事:

http://guides.rubyonrails.org/active_record_migrations.html#passing-modifiers

18
13
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
18
13