LoginSignup
3
2

More than 1 year has passed since last update.

Rails モデルの作成方法メモ

Last updated at Posted at 2022-06-04

Railsのモデル作成方法の備忘録です。

環境

macOS Monterey 12.3.1
ruby 3.1.2
rails 6.1.6

モデルとは

MVC構造のM。DBとのデータの連携を担当する。

モデル作成コマンド

ターミナル
rails g model モデル名 カラム名1:データ型 カラム名2:データ型 ...

ggenerateの略。

例: Userモデルを作成する

ターミナル
rails g model User name:string email:string

コマンドによりapp/modelsディレクトリ下にモデルファイル、db/migrateディレクトリ以下にマイグレーションファイルが作成される。

マイグレーションファイルの確認、修正

コマンドにより作成されたマイグレーションファイルを確認する。

(タイムスタンプ)_create_users.rb
class CreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end

ここでカラム名やデータ型、デフォルト値、NULLを許容するか等を修正する。

(タイムスタンプ)_create_users.rb
class CreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      t.string :name, :null => false  #追加
      t.string :email, :null => false  #追加

      t.timestamps
    end
  end
end

カラムの制約はバリデーションと合わせて設定した方が良い。
参考:https://qiita.com/rockettetsu/items/4d0fc754ab2e2aca7c13

外部キーの設定方法:

マイグレーションの実行

確認と修正が終わったらマイグレーションを実行する。

ターミナル
rails db:migrate

DBにUserテーブルが作成される。

ターミナル
== (タイムスタンプ) CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.0499s
== (タイムスタンプ) CreateUsers: migrated (0.0510s) =============================
3
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
3
2