LoginSignup
0
0

More than 3 years have passed since last update.

Ruby on RailsでDBのカラム追加をしてみた。

Last updated at Posted at 2019-09-10

1.はじめに

1-1.現在のDBの確認

$ rails dbconsole
SQLite version 3.24.0 2018-06-04 14:10:15
Enter ".help" for usage hints.
sqlite> 
sqlite> .headers on
sqlite> select * from stores;

id|name|name_hurigana|smoking|created_at|updated_at|prefecture|city
1|山手十番館|(ヤマテジュウバンカン)|分煙|2019-08-29 12:57:40.109863|2019-08-29 12:57:40.109863

まずは現状のカラムの確認
id|name|name_hurigana|smoking
上記の4つが最初に作成した、カラムになります。

sqlite> .headers onを行わないとカラムが表示されないので注意

2.手順

2-1.DBのカラム追加

$ rails generate migration AddColumnToStore prefecture:string city:string

Column To Storeの最初の文字は大文字
Store のところに追加したいモデルを記入
prefecture:string city:string DB作成する時同様の名前とフォーマットの設定

2-2.ファイルが作成されるので確認

20190829091622_add_detail_to_store.rb
class AddDetailToStore < ActiveRecord::Migration[5.2]
  def change
    add_column :stores, :prefecture, :string
    add_column :stores, :city, :string
  end
end

実行を完了後は上記のようにファイルが作成されます。

2-3.DBの更新

rake db:migrate

忘れてはいけないmigrate
これでDBの追加完了。

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