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

プログラミング学習 記録 13章 1

0
Posted at

13章 MicropostとUserの関連付け

  1. UserとMicropostを関連付ける
  2. Twitterを参考にMicropostを改良する
  3. Userが破棄されたら関連付けられたMicropostも破棄される

モデル作成

いつも通り rails g model Micropost content:text user:referencesとしマイクロポストのモデルを作成する

このときuser:referencesという引数は生成されたMicropostモデルの中で自動的にbelongs_to:userが追加される(今回のキーワード)

app/models/micropost.rb
class Micropost < ApplicationRecord
  belongs_to :user
end

ちなみにこのMicropostはApplicationRecordを継承している

references型

referencesを利用すると自動的にindexと外部キー参照付きの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

ここに記載されているadd_index :microposts, [:user_id, :created_at]user_idcreated_atを付与するとuser_idに関連付けられたすべてのマイクロポストを作成時刻の逆順で取り出しやすくなるらしい。感覚的にわかる

User/Micropostの関連付け

Twitter民ならわかると思うが、今回のUserとMicropostの関係性は
MicropostとそのUserは belongs_to (1対1),
UserとそのMicropostは has_many (1対多)
となる

つまりMicropostには

app/models/micropost.rb
class Micropost < ApplicationRecord
  belongs_to :user
end

Userには

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

関連付けられる

validation

慣習的なのでスキップ

Micropostを降順にする

今のままでは昇順(古いやつから上)に表示されるので、これを降順(新しいのを上)で表示させる

app/models/micropost.rb
class Micropost < ApplicationRecord
  belongs_to :user
  default_scope -> { order(created_at: :desc) }
  validates :user_id, presence: true
  validates :content, presence: true, length: { maximum: 140 }
end

**default_scope -> { order(created_at: :desc) }**で解決

Dependent: destroy

ユーザーが削除されたなら関連付けられたMicropostも一緒に削除されなければならない
これには

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

dependent: :destroyで解決
このオプションを使うと、ユーザーが削除されたと同時に紐づいたマイクロポストも削除されるようになる

今回はここまで

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?