1
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 5 years have passed since last update.

UserモデルとMicropostモデルとの関連付け

Last updated at Posted at 2018-12-24

Ruby on Railsチュートリアルの13章にて、2つの異なるモデル(デーブル)同士の関連付けについて
解説しており、理解を深めるため、アウトプット。

Micropostモデルの生成

Userモデル(あらかじめ生成済み)に関連付けさせるMicropostモデルをrailsコマンドにて生成する。

$ rails generate model Micropost content:text user:references

上記コマンドにより、ApplicationRecordを継承したモデルが作られる。
※この時、Userテーブル作成時同様、micropostsテーブルを作成するための
マイグレーションファイルも自動的に生成される。
 

user:referencesという引数を含めて、コマンドを実行すると、
ユーザーと1対1の関係であることを表すbelongs_toのコードが
Micropostモデルのファイルに追加される。

app/models/micropost.rb
class Micropost < ApplicationRecord
   belongs_to :user # この行が追記される。
end

 

さらに、自動生成されたMicropostモデルのマイグレーションファイルでは、自動的に
インデックスと外部キー参照付きのuser_idカラムが追加され、UserとMicropostを
関連付けする下準備をしてくれる。

db/migrate/[timestamp]_create_microposts.rb
class CreateMicroposts < ActiveRecord::Migration[5.0]
  def change
    create_table :microposts do |t|
      t.text :content
      t.references :user, foreign_key: true

      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at] # ここの行!
  end
end

※user_idとcreated_atの両方を1つの配列に含めている点にも注目。
こうすることでActive Recordは、両方のキーを同時に扱う複合キーインデックス
(Multiple Key Index) を作成する。(複合キーインデックスの理解は後日。)  
 

はじめに実行したrailsコマンドにより、下記テーブルが作成される。
micropost_model_3rd_edition.png

UserテーブルとMicropostテーブルの関連付け

Micropostテーブル作成時にファイルに追記されたbelongs_toと

app/models/micropost.rb
class Micropost < ApplicationRecord
   belongs_to :user # この行。
end

Userテーブルのファイルに**has_many(1対多の関係を示す)**を手動で追記

app/models/user.rb
class User < ApplicationRecord
  has_many :microposts
  .
  .
  .
end

すると、以下のメソッドがrailsで使用出来るようになる。

メソッド 用途
micropost.user Micropostに紐付いたUserオブジェクトを返す
user.microposts Userのマイクロポストの集合をかえす
user.microposts.create(arg) userに紐付いたマイクロポストを作成する
user.microposts.create!(arg) userに紐付いたマイクロポストを作成する (失敗時に例外を発生)
user.microposts.build(arg) userに紐付いた新しいMicropostオブジェクトを返す
user.microposts.find_by(id: 1) userに紐付いていて、idが1であるマイクロポストを検索する

これらのメソッドを用いると、紐付いているユーザーを通して
マイクロポストを作成したりすることが出来る。

例)

railsコンソールにて
user = User.find(1)
micropost = user.microposts.build(content:"hoge")
# micropost変数のuser_idには、関連するユーザーのid(この場合はid:1)が自動的に設定される。
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?