This is the presentation I gave at the "First LT Meeting #2" for the students on May 9, 2020.
RailsͰϑΥϩʔػೳΛ࡞ΔͨΊͷϞσϧͷॻ͖ํϑΟϤϧυϒʔτΩϟϯϓ ΦϯϥΠϯLTձima1zumi2020-05-09
View Slide
ࣗݾհ- @ima1zumiʢࠓઘ ຑཬʣ- ҎલSIerͰCOBOLͱ͔DB৮ͬͯ·ͨ͠- Rails ϢʔβʔϑΥϩʔͷϓϥΫςΟεத- ࠷ۙͷझຯɿ͋ͭɺίʔώʔɺࣗ։ൃڥΛ͍͍ײ͡ʹ͢Δ͜ͱ
ςʔϚΛબΜͩཧ༝- ϢʔβʔϑΥϩʔͰϞσϧʹॻ͘belongs_toͱ͔has_many͕ढจʹݟ͑Δ- ಡΈํ͕͔Βͳͯ͘Μͩ
͜Ε͔Β͢͜ͱ- ϑΥϩʔػೳΛ࡞ΔʹɺσʔλϕʔεΛͲ͏࡞Ε͍͍ͷ͔ʢσʔλϕʔεͷʣ- ͦΕΛRailsͰͲ͏ఆٛ͢Δͷ͔ʢRailsͷʣ
ϑΥϩʔɾϑΥϩϫʔͷؔͪΌͪΌ·ΔδϡϯΛϑΥϩʔ͍ͯ͠Δ(following)δϡϯͪΌͪΌ·ΔʹϑΥϩʔ͞Ε͍ͯΔ(followed)ͪΌͪΌ·Δ δϡϯfollowingfollowed
ྫɿϢʔβʔදJE OBNF ͪΌͪΌ·Δ αϒϨ δϡϯ
ϑΥϩʔΛ࣮͢ΔʁJE OBNF GPMMPXFS@JE GPMMPXFE@JE ͪΌͪΌ·Δ αϒϨ δϡϯ
JE OBNF GPMMPXFS@JE GPMMPXFE@JE ͪΌͪΌ·Δ αϒϨ δϡϯ - 1ͭͷηϧʹෳͷ͕ೖΔ- ֤ྻͷΛҰҙʹܾΊΒΕͳ͘ͳΔͷͰɺDBͰNG
2ͭͷςʔϒϧΛ͏6TFSJE OBNF ͪΌͪΌ·Δ αϒϨ δϡϯGSJFOETIJQGPMMPXFS@JE GPMMPXFE@JE
RailsͰ͜ͷؔΛදݱ͢Δʹʁ- RailsͰɺΞϓϦέʔγϣϯ͕ѻ͏σʔλͱखଓ͖Ϟσϧʹॻ͘- UserϞσϧͱFriendshipϞσϧ- ̎ͭͷϞσϧͷؒʹ͕ؔ͋Δ͜ͱΛఆٛ͢Δ- belongs_to, has_manyΛ͏
belongs_toؔ࿈͚- ࣗͷϞσϧͱ૬खͷϞσϧ͕1:1ͷؔͰ͋Δ- ଞํͷϞσϧʹॴଐ(belongs_to)͢Δ- book ͔Βݟͯ author(ஶऀ)ඞͣ1ਓҾ༻ɿIUUQTSBJMTHVJEFTKQBTTPDJBUJPO@CBTJDTIUNM
FriendshipϞσϧclass Friendship < ApplicationRecordbelongs_to :follower, # 関係の名前class_name: "User" # 関係先モデル名belongs_to :followed,class_name: "User"end6TFSJE OBNF ͪΌͪΌ·Δ αϒϨ δϡϯGSJFOETIJQGPMMPXFS@JE GPMMPXFE@JE 'SJFOETIJQͱ6TFSͷؔ
has_manyؔ࿈͚Ҿ༻ɿIUUQTSBJMTHVJEFTKQBTTPDJBUJPO@CBTJDTIUNM- ࣗͷϞσϧͱ૬खͷϞσϧͱ͕1:ଟͷؔͰ͋Δ- ૬खͷϞσϧΛॴ༗(has_many)͢Δ- author ෳͷ book Λ࣋ͪ͏Δ
UserϞσϧ(following) 1class User < ApplicationRecordhas_many :active_relationships, # Friendshipの言い換えclass_name: "Friendship", # 関連先クラス名foreign_key: "follower_id", # 関連するカラム名dependent: :destroy # 関連先が削除されたときに削除する...end6TFSJE OBNF ͪΌͪΌ·Δ αϒϨ δϡϯGSJFOETIJQGPMMPXFS@JE GPMMPXFE@JE 6TFSͱ'SJFOETIJQଟͷؔ
UserϞσϧ(following) 2class User < ApplicationRecord...has_many :following, # カラム名through: :active_relationships, # active_relationshipsを通してsource: :followed # 関連付け先モデル名...end6TFS͕BDUJWF@SFMBUJPOTIJQTΛ௨ͯ͠GPMMPXFEͱଟɿଟͷؔΛ࡞Δ
UserϞσϧ(followed)class User < ApplicationRecordhas_many :passive_relationships,class_name: "Friendship",foreign_key: "followed_id",dependent: :destroyhas_many :followers,through: :passive_relationships,source: :follower...endGPMMPXJOHͱ΄΅ಉ͡˞TPVSDFGPMMPXFSඞਢͰͳ͍͕GPMMPXJOHͱܗΛ͋ΘͤΔͨΊʹॻ͍ͯ͋Δ
σʔλͷؔ࿈͚͕Ͱ͖ͨϑΥϩʔػೳΛ࣮͢Δʹfollow/unfollowϝιουΛ࡞ͬͨΓɺίϯτϩʔϥͱϏϡʔΛ࣮ͨ͠Γ͢Δඞཁ͕͋Δ͕ɺ͜ͷLTͰׂѪ
Ϟσϧಉ࢜ͷؔhas_many, belongs_toͳͲͰදͤΔϞσϧ໊ͷݴ͍͑Λͯ͠ɺUserͱFriendshipʹfollowerͱfollowedͷ2ͭͷؔΛ࡞Δ·ͱΊ
ࢀߟจݙͳͲୡਓʹֶͿ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/201629RailsνϡʔτϦΞϧ ୈ14ষ ϢʔβʔΛϑΥϩʔ͢Δhttps://railstutorial.jp/chapters/following_users?version=5.1#cha-following_userskeynoteςϯϓϨʔτhttps://github.com/yulily100/Material-Color-Keynotehighlighthttps://github.com/taggon/highlight