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

Caching associations in rails

Avatar for horikawa horikawa
August 14, 2019

Caching associations in rails

Avatar for horikawa

horikawa

August 14, 2019
Tweet

More Decks by horikawa

Other Decks in Technology

Transcript

  1.  

  2.  

  3. ҎԼͷϞσϧ͕͋ͬͨ৔߹   app/models/user.rb class User < ApplicationRecord has_many :memos

    end app/models/memo.rb class Memo < ApplicationRecord belongs_to :user end
  4. N + 1͕ൃੜ͢Δ N(memo.userͷ਺) + 1(Memo.allͷΞΫηε) SELECT 'memos'.* FROM 'memos'

    # Memo.allͷΞΫηε # memo.user.nameͷΞΫηε SELECT 'users'.* FROM 'users' WHERE 'users'.'id' = 1 LIMIT 1 SELECT 'users'.* FROM 'users' WHERE 'users'.'id' = 2 LIMIT 1 SELECT 'users'.* FROM 'users' WHERE 'users'.'id' = 3 LIMIT 1  
  5. includes, preload, eager_load Λ࢖͑͹ྑ͍   @memos = Memo.all.includes(:user) @memos.each

    do |memo| memo.id memo.user.name end SELECT 'memo'.* FROM 'memos' SELECT 'users'.* FROM 'users' WHERE 'users'.'id' IN (1, 2, 3) N + 1→1 + 1ʹͳΔ
  6. N + 1ΛղܾͰ͖Δ͔൱͔ • N + 1ΛղܾͰ͖ͳ͍ • joins •

    N + 1ΛղܾͰ͖Δʢؔ࿈ςʔϒϧ৘ใΛؚΊͯΩϟογϡ͢Δʣ • eager_load • LEFT OUTER JOINΛར༻͢Δʢt0_r0Έ͍ͨͳ΍ͭʣ • preload • IN۟Λར༻ͯ͠ɺෳ਺ΫΤϦͰऔͬͯ͘Δ • whereͰؔ࿈ςʔϒϧͷ৘ใΛߜΕͳ͍ • includes • eager_load, preloadΛঢ়گʹԠͯ͡ɺ࢖͍෼͚͢Δ  
  7. ؔ࿈ઌςʔϒϧͷΧϥϜΛ࡟আ ͍ͨ͠ͱ͢Δ • લఏ৚݅ • ↓ͷίʔυ͕ଘࡏ͢Δ • ΞϓϦέʔγϣϯίʔυ͔Βɺ 
 deprecated_columnΛࢀর͠ͳ͍Α͏ʹमਖ਼ࡁΈ

      @memos = Memo.includes(:user).where(users: { name: ‘horikawa’ }) @memos.each do |memo| memo.id memo.user.name end
  8. ౴͑ • ؔ࿈ςʔϒϧͷΩϟογϡΛऔಘ͢Δࡍʹɺ
 શͯͷΧϥϜ৘ใΛSELECTจͰࢦఆͨ͠ΫΤϦΛൃߦ͠Α͏ͱ͢Δ (SELECT … `users`.`id` AS t1_r0, `users`.`deprecated_column`

    AS t1_r1)
 ↓ • ϚΠάϨʔγϣϯͰɺΧϥϜΛ࡟আ͢Δ
 ˣ • ΫΤϦΛ࣮ߦ͢ΔࡍʹɺΩϟογϡΛ࢖͏ͷͰɺ
 ଘࡏ͠ͳ͍ΧϥϜʹର͢ΔΞΫηεΛͯ͠ɺΤϥʔ͕ग़Δ  
  9. ౴͑   # whereͰ৚݅෼ذ͢Δͱɺleft outer joinͰΩϟογϡΛੜ੒͢Δ @memos = Memo.includes(:user).where(users:

    { name: ‘horikawa’ }) # ॲཧ͕͜͜Βลʹ͍ΔλΠϛϯάͰɺΧϥϜΛ࡟আ͞Εͯ͠·͏ͱ… # memo.deprecated_column͕ͳ͍ͱΤϥʔ͕ग़Δ @memos.each do |memo| memo.id memo.user.name end