3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】db/schema.rbファイルとは何か?役割

Posted at

rails db:migrateでマイグレーションすると、db > schema.rbが更新される。このファイルの役割は何かについて。


##schema.rbファイルとは? schema(スキーマ)と名前がついているだけあって、DBの構造を示すデータ。

DBのスキーマをそのままキャプチャしたもの。最新のDBの状態が反映されている


##schema.rbの活用 DBの構造を確認したい時に、このファイルを見ればすぐにわかる。

DBやテーブルが多い場合はファイルの中身はかなり長いものになる。

image.png


**▼schema.rbの生成例**
#マイグレーションファイルの作成とマイグレーション
$ rails g scaffold Tweeet tweeet:text
$ rails db:migrate

image.png

▼ファイルの中身

schema.rb
ActiveRecord::Schema.define(version: 2021_03_19_063511) do

  create_table "tweeets", force: :cascade do |t|
    t.text "tweeet"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

テーブル名とカラムの型とバリデーションが表示される。
上記例の場合は、テーブル名 tweeets。カラムは、tweet, created_at, updated_atの3つ。

##参考
https://railsguides.jp/active_record_migrations.html


###マイグレーションの状況を確認する schema.rbの中にはマイグレーションをいつ実施し、どんなテーブルを作成したかの情報が入っている。以下のコマンドで確認できる。

$ rails db:migrate:status

$ rails db:migrate:status

database: db/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20210319063511  Create tweeets
3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?