Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Railsでフォロー機能を作るためのモデルの書き方

 Railsでフォロー機能を作るためのモデルの書き方

This is the presentation I gave at the "First LT Meeting #2" for the students on May 9, 2020.

ima1zumi

May 09, 2020
Tweet

More Decks by ima1zumi

Other Decks in Programming

Transcript

  1. ໰୊఺ JE OBNF GPMMPXFS@JE GPMMPXFE@JE  ͪΌͪΌ·Δ   

      αϒϨ    δϡϯ   - 1ͭͷηϧʹෳ਺ͷ஋͕ೖΔ - ֤ྻͷ஋ΛҰҙʹܾΊΒΕͳ͘ͳΔͷͰɺDBͰ͸NG 
  2. 2ͭͷςʔϒϧΛ࢖͏ 6TFS JE OBNF  ͪΌͪΌ·Δ  αϒϨ  δϡϯ

    GSJFOETIJQ GPMMPXFS@JE GPMMPXFE@JE         
  3. FriendshipϞσϧ class Friendship < ApplicationRecord belongs_to :follower, # 関係の名前 class_name:

    "User" # 関係先モデル名 belongs_to :followed, class_name: "User" end  6TFS JE OBNF  ͪΌͪΌ·Δ  αϒϨ  δϡϯ GSJFOETIJQ GPMMPXFS@JE GPMMPXFE@JE         'SJFOETIJQͱ6TFS͸ͷؔ܎
  4. UserϞσϧ(following) 1 class User < ApplicationRecord has_many :active_relationships, # Friendshipの言い換え

    class_name: "Friendship", # 関連先クラス名 foreign_key: "follower_id", # 関連するカラム名 dependent: :destroy # 関連先が削除されたときに削除する ... end  6TFS JE OBNF  ͪΌͪΌ·Δ  αϒϨ  δϡϯ GSJFOETIJQ GPMMPXFS@JE GPMMPXFE@JE         6TFSͱ'SJFOETIJQ͸ଟͷؔ܎
  5. UserϞσϧ(following) 2 class User < ApplicationRecord ... has_many :following, #

    カラム名 through: :active_relationships, # active_relationshipsを通して source: :followed # 関連付け先モデル名 ... end 6TFS͕BDUJWF@SFMBUJPOTIJQTΛ௨ͯ͠ GPMMPXFEͱଟɿଟͷؔ܎Λ࡞Δ
  6. UserϞσϧ(followed) class User < ApplicationRecord has_many :passive_relationships, class_name: "Friendship", foreign_key:

    "followed_id", dependent: :destroy has_many :followers, through: :passive_relationships, source: :follower ... end  GPMMPXJOHͱ΄΅ಉ͡ ˞TPVSDFGPMMPXFS͸ඞਢͰ͸ͳ͍͕GPMMPXJOH ͱܗΛ͋ΘͤΔͨΊʹॻ͍ͯ͋Δ
  7. ࢀߟจݙͳͲ ୡਓʹֶͿDBઃܭ పఈࢦೆॻ https://www.amazon.co.jp/dp/B00EE1XPAI/ RailsΨΠυ Active Record ͷؔ࿈෇͚ https://railsguides.jp/association_basics.html ʲRailsνϡʔτϦΞϧʳϑΥϩʔػೳͷΞιγΤʔγϣϯΛղઆͯ͠ΈΔ

    https://sado-tech.hateblo.jp/entry/2018/08/17/201629 RailsνϡʔτϦΞϧ ୈ14ষ ϢʔβʔΛϑΥϩʔ͢Δ https://railstutorial.jp/chapters/following_users?version=5.1#cha-following_users keynoteςϯϓϨʔτ https://github.com/yulily100/Material-Color-Keynote highlight https://github.com/taggon/highlight