LoginSignup
1
0

More than 1 year has passed since last update.

【Rails】references型

Last updated at Posted at 2022-03-02

references型って?

自動的にインデックスと外部キー参照付きのカラムが追加され既存のモデルと生成したモデルを関連付けする下準備をしてくれる。
つまり、既存のテーブルを参照して必要なカラムを自動的に追加して新しいテーブルを作成すること。
*すべてのデータベースで使えるわけではない。

例)

Micropostモデルを作成

# userテーブルに紐付けて、Micropostテーブルを作成
$ rails generate model Micropost content:text user:references

自動生成されたMicropostモデル

micropost.rb
class Micropost < ApplicationRecord
   # belongs_toメソッドでuserモデルに紐付いている(自動的に記述してくれてある)
   belongs_to :user
end

Micropostのマイグレーション

[timestamp]_create_microposts.rb
class CreateMicroposts < ActiveRecord::Migration[6.0]
  def change
    create_table :microposts do |t|
      # contentというstringカラム
      t.text :content
      # user参照で外部キー有効
      t.references :user, foreign_key: true
      # imestampsカラム(created_at, update_at)
      t.timestamps
    end
    # user_idとcreated_atカラムにインデックス付与のため記述
    add_index :microposts, [:user_id, :created_at]
  end
end

user_idに関連付けられたすべてのマイクロポストを作成時刻の逆順で取り出しやすくなる。
下記のように配列を書くことによってActive Recordが、両方のキーを同時に扱う複合キーインデックスを作成する。

add_index :microposts, [:user_id, :created_at]

UserモデルにMicropostモデルを紐付ける

user.rb
class User < ApplicationRecord
  # has_manyメソッドでmicropostsモデルに紐付いている(自動で追加されないので手動で追加)
  has_many :microposts
  .
  .
end
1
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
1
0