LoginSignup
2
8

More than 3 years have passed since last update.

カラムの型

Last updated at Posted at 2019-10-05

カラムをすぐに忘れてしまうので、使ったものから追記していく完全な個人メモ帳です。

型名 説明
string 文字列型 255文字まで
text 長い文字列
integer 整数
boolean Boolean(真偽値)
float 浮動小数点数型 google maps APIの緯度、経度で使用

カラムの追加

カラム追加用のマイグレーションファイル作成
$ rails g migration Addカラム名Toテーブル名 カラム名:型名
例 rails g migration AddLatitudeToMaps latitude:float
生成されたマイグレーションファイル
class AddLatitudeToMaps < ActiveRecord::Migration[5.2]
  def change
    add_column :maps, :latitude, :float
    add_column :maps, :longitude, :float #ここでさらに追記してもOK
  end
end
実行
$ bundle exec rake db:migrate

カラムの削除

カラム削除用のマイグレーションファイル作成
$ rails generate migration Removeカラム名Fromテーブル名 カラム名:型名
例)$ rails generate migration RemoveCommentFromMaps comment:text
作成されたマイグレーションファイル
class RemoveCommentFromMaps < ActiveRecord::Migration[5.2]
  def change
    remove_column :maps, :comment, :text
  end
end
実行
$ bundle exec rake db:migrate

カラムの型を変更する

マイグレーションファイルを作成
$ rails g migration change_datatype_カラム名 _ of _ テーブル名
例)$ rails g migration change_datatype_recommended_of_maps
作成されたマイグレーションファイル
class ChangeDatatypeRecommended < ActiveRecord::Migration[5.2]
  def change
    change_column :maps, :recommended, :text #変更したいカラムの型を書く
  end
end
実行
$ bundle exec rake db:migrate
2
8
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
2
8