LoginSignup
3
4

More than 3 years have passed since last update.

[Ruby on Rails]データベースの作成、カラムの追加

Posted at

いつも忘れるのでRubyonRailsでのデータベースの作成、カラムの追加についてメモ

データベース作成

まずはデータベースへの変更指示を記述するマイグレーションファイルを作成する
モデル(User)も同時に作成される。カラムは(パラメーター名):(変数の型)で設定
コマンドラインでカラム設定しないでファイルに直書きでもOK

terminal
rails g model User name:text address:text age:integer

次にマイグレーションファイル内容を実行する

terminal
rails db:migrate

上のコマンドの代わりにこっちでも実行できるけど違いは分かりません(調べます)

terminal
bundle exec rake db:migrate

カラム追加

まずマイグレーションファイルを任意の分かりやすいファイル名で作成

terminal
rails g migration add_occupation_to_users

次に作成したマイグレーションファイルに変更内容を書き込む

add_occupation_to_users.rb
class AddOccupationToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :occupation, :string
  end
end

そしたら再びマイグレーションファイル実行

terminal
rails db:migrate
3
4
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
3
4