LoginSignup
0
0

More than 5 years have passed since last update.

Ruby on Rails [学習記録-第16章-] カラムの追加/削除

Last updated at Posted at 2019-06-23

rails generate migrationコマンド

  • テーブルにカラムを追加したり、削除するようなテーブルの構造を変えたいときもマイグレーションファイルを作成する。
  • rails generate migrationに続けてクラス名を指定。
$ bundle exec rails g migration AddRateToProducts
  # => マイグレーションファイルの作成
  • メソッドchangeの中にテーブル構造の変更を書く。
class AddRateToProducts < ActiveRecord::Migration[5.2]
  def change
  end
end

add_column

  • add_columnをマイグレーションファイルのchangeメソッド内に書くとカラムの追加ができる。
add_column :テーブル名, :カラム名, :カラムの型
  • 例としてBooksテーブルにInteger型のカラムpriceを追加する際は以下のように書く。
class AddPriceToBooks < ActiveRecord::Migration[5.2]
  def change
    add_column :books, :price, :integer
  end
end

remove_column

  • 同様にカラムの削除はremove_columnで行う。
remove_column :テーブル名, :カラム名, :カラムの型

テーブルへ反映

  • マイグレーションファイルに書いたテーブルの変更内容をテーブルに反映させるにはターミナルでrake db:migrateコマンドを実行。
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