LoginSignup
0
1

More than 3 years have passed since last update.

【RubyonRails入門】テーブルにカラムを追加する方法

Last updated at Posted at 2019-09-10

【目標】testsテーブルに、mailカラムを追加する

1. migrationファイルを追加する

【基本形】rails g migration add_追加したいカラム名_to_テーブル名 追加したいカラム名:データ型

$ rails g migration add_mail_to_tests mail:string
db/migrate/20190825031340_add_mail_to_tests.rb
# 自動で追加されたファイルの内容
class AddMailToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :tests, :mail, :string
  end
end

2. 追加したmigrationファイルを、DBに追加する

$ rails db:migrate

3. その他、補足など

3-1. rails g migrationrails g modelの違い

$ rails g migration add_mail_to_tests mail:string
=> 指定したmigrationファイルのみを作成する
$ rails g model
=> model と migrationファイルを作成する

3-2. 初心者のための注意点

【注意】以下のファイル内容は、自分で絶対にいじらない
・db/migrate/20190825015302_create_tests.rb
・db/schema.rb
【理由】 rails db:migrateで自動生成しているファイルだからだそうです

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