LoginSignup
1
2

More than 5 years have passed since last update.

RailsでMySQLのテーブル作成

Last updated at Posted at 2017-10-07

Railsでテーブルを作成する方法をまとめました。

環境

  • CentOS6.5
  • Rails 5.1.4
  • MySQL 5.7

*ここからはRails環境、MySQLが使えるという前提で説明していきます。

基本

Usersというテーブルを作ってみます。

カラムは

  • uuid (データ型:string)
  • name (データ型:string)
  • age (データ型:integer)

Railsコマンドでマイグレーションファイルを作成

$ rails g model User uuid:string name:string age:integer
invoke  active_record
create    db/migrate/20171007062120_create_users.rb
create    app/models/user.rb
invoke    test_unit
create      test/models/user_test.rb
create      test/fixtures/users.yml

コマンドの意味を説明します。

User = テーブル名の単数形(実際にはUsersというテーブルが作成される。仮にここに「Users」と入れると怒られる。でもUsersっていうテーブルを作るのね、って解釈される)

uuid:string = カラム名:データ型 という関係

色々作成されましたね。ここで重要なのはマイグレーションファイルである db/migrate/20171007062120_create_users.rb ですのでちょっと覗いてみましょう。

$ cat db/migrate/20171007062120_create_users.rb
class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :uuid
      t.string :name
      t.integer :age

      t.timestamps
    end
  end
end

こんな感じになってるはずです。create_tableでusersっていうテーブル作るんだな。カラムはuuid、name、ageとかなんだなっていうのがなんとなくわかるはずです。

RailsコマンドでマイグレーションファイルをDBに反映

先ほど作成したマイグレーションファイルを

rails db:migrate
== 20171007062120 CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.0410s
== 20171007062120 CreateUsers: migrated (0.0411s) =============================

これでテーブルが作成されているはずです。

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