0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】yyyymmddhhmmss_create_[テーブル名].rbについて

Last updated at Posted at 2025-04-07

記事概要

Ruby on Railsのマイグレーションファイルについて、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している

基本情報

ファイルパス

db/migrate/yyyymmddhhmmss_create_[テーブル名].rb

記載方法

yyyymmddhhmmss_create_[テーブル名].rb
class Create[モデル名の複数形] < ActiveRecord::Migration[7.1]
  def change
    create_table :[テーブル名] do |t|
      # カラムを追加
      t.timestamps
    end
  end
end

カラムは下記のように記述する

t. :カラム名

t.text :memo

まとめ

カラムの型

カラムの型 説明 用途
integer 数値 金額、回数など
string 文字(短文) ユーザー名、メールアドレスなど
text 文字(長文) 投稿文、説明文など
boolean 真か偽か はい・いいえの選択、合格・不合格のフラグなど
datetime 日付と時刻 作成日時、更新日時など

NOT NULL制約

テーブルの属性値にNULL(空の値)が入らないように制限する制約

t. :カラム名, null: false

t.string :name, null: false

一意性制約

テーブル内で重複するデータを禁止する制約

t. :カラム名, unique: true

t.string :email, unique: true

※Gemのdeviseを使用する場合、デフォルトでemailカラムに一意性制約が付与されるため、手動でunique: trueを記載する必要はない

外部キー制約

外部キーの元になるデータと参照するデータの整合性を保証する制約

t.references :カラム名,  foreign_key: true

# user_idカラムが作成される
t.references :user, foreign_key: true

Ruby on Railsまとめ

テーブル

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?