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?

More than 1 year has passed since last update.

カラムに指定するreferences型とは?

0
Posted at

はじめに

カラム作成時に使う型は様々ありますが、references型というものを改めて学んだのでアウトプットしたいと思います。

references型とは?

references(直訳すると”参照”)型とは、新規作成するテーブルのカラムに、もともとあるテーブルを指定する場合に使います。

使用する方法

rails g model comment board:references name:string comment:text

こちらを解説します。
commentテーブルに”board:references”と書くとBoardモデルと紐づけるためのboard_idカラムが作成されます。
後ろのnameとcommentのカラムは従来通りの記述ですね。

models/comment.rbを開くと

class Comment < ApplicationRecord
  belongs_to :board #ここが追加されます
end

”belongs_to :board”が自動で追記されます。
これは、commentに対してboardは1つしかないという事を表します。
逆の意味が has_manyになりますね。1対多ってやつです。
has_manyは自分で記述します。

最後にマイグレーションファイルを見ると

class CreateComments < ActiveRecord::Migration[6.1]
  def change
    create_table :comments do |t|
      t.references :board, null: false, foreign_key: true #ここがreferencesの文章!
      t.string :name, null: false
      t.text :comment, null: false
      t.timestamps
    end
  end
end

こんな感じになってます。
t.references
カラムが他のテーブルを参照しているという事

null: false
空欄を許可しないという事

foreign_key: true
外部キーであるという事
外部キーとは
指定したカラムの値のみしか使えないようにす制限の事

おわりに

rails db:migrateをしたら完成です!
ありがとうございました^^

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?