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

良いアプリケーションは良いデータベースに宿る

Bf6309706fc0e12ee0349979a5e29b6e?s=47 Ya-Suzuki
November 27, 2019

 良いアプリケーションは良いデータベースに宿る

2019/11/27 Classi Rails Night

Bf6309706fc0e12ee0349979a5e29b6e?s=128

Ya-Suzuki

November 27, 2019
Tweet

Transcript

  1. ྑ͍ΞϓϦέʔγϣϯ͸ ྑ͍σʔλϕʔεʹ॓Δ 2019.11.27 Classi Rails Night ླ໦߁म(@y_s____731)

  2. • ླ໦߁म • AGBIOTECHגࣜձࣾ • Ruby/Rails/ΤϯδχΞྺ 3೥໨ • લ৬͸T̋Y̋TAͰઃඋͷमཧͯ͠·ͨ͠ɻ •

    twitter @y_s_____731
  3. લஔ͖

  4. σʔλϕʔεɾɾɾ • ೔ʑ͞ΘͬͯΔ͸ͣ • ҙࣝͤͣͱ΋͞ΘΕͯ͠·͏ • RailsʢActiveRecordʣͷੌ͞

  5. ͳ͔ͳ͔ݴٴ͞Εͳ͍

  6. ͍͟ຊ൪؀ڥˠແࣄࢮ๢

  7. σʔλϕʔεΛ஌Βͣʹ ྑ͍ΞϓϦέʔγϣϯ͸࡞Εͳ͍

  8. None
  9. Classi͞ΜͷΠϕϯτ͕ ݸਓతʹλʔχϯάϙΠϯτ

  10. 1.໊લॏཁ

  11. ͦΜͳ͜ͱ΋͋ͬͯɺࢲͷઃܭ্ͷ࠲ӈͷ໏͸ʮ໊લॏཁʯ Ͱ͢ɻ ͋ΒΏΔػೳΛσβΠϯ͢Δ࣌ʹɺࢲ͸ͦͷ໊લʹ΋ͬͱ΋ ͩ͜ΘΓ·͢ɻ ϓϩάϥϚͱͯ͠ͷΩϟϦΞͷதͰɺద੾ͳ໊લΛ͚ͭΔ͜ ͱ͕Ͱ͖ͨػೳ͸੒ޭ͠ɺͦ͏Ͱͳ͍ػೳʹ͍ͭͯ͸ޙͰޙ չ͢Δ͜ͱ͕ଟ͔ͬͨΑ͏ʹࢥ͏͔ΒͰ͢ɻ by Matz

  12. σʔλϕʔε΋ಉ͡

  13. σʔλϕʔεʹ͓͚Δ໊લɾɾɾ • ςʔϒϧ໊ • ΧϥϜ໊

  14. ୭͕Ͳ͏Έͯ΋ɺԿΛදͯ͠Δ͔෼͔Δ

  15. ந৅× ۩ମత̋ ʢUser → Teature, Studentͱ͔ʣ ந৅తͳ໊લ͸੹຿͕ᐆດʹͳΓ͕ͪ ↪︎FatModelʹͳΓ΍͍͢

  16. ུ͞ͳ͍ ʢྫ.༵೔ dow× day_of_week̋ʣ ಛʹαʔϏεݻ༗ͷݴ༿ͳͲུ͞ΕΔͱ ޙ͔Βೖͬͨਓ͸͖ͬͱਏ͍

  17. 2.੍໿Λ׆༻͢Δ

  18. ੍໿ RDBMS͕ඪ४Ͱ͍࣋ͬͯΔ ೖྗ஋Λ੍ݶ͢Δػೳ

  19. ੍໿ͷछྨɾɾɾ • NOT NULL੍໿ • ForeignKey(֎෦Ωʔ)੍໿ • UNIQUE੍໿ • CHECK੍໿…etc

  20. NOT NULL ੍໿ NULLΛېࢭ͢Δ

  21. class CreateArticles < ActiveRecord::Migration[5.2] def change create_table :articles do |t|

    t.string :title, null: false t.text :content, null: false t.timestamps end end end
  22. ࠷ॳʹ͚ͭΔͷ͸؆୯ɻ Ͱ΋ɺޙ͔Β௥Ճ͠ਏ͍͜ͱ΋ɻ

  23. جຊతʹNOT NULL͚ͭΔ ↓ Կ͕NULLABLEͳͷ͔Λߟ͑Δ

  24. ֎෦Ωʔ ੍໿ ผͷςʔϒϧͷಛఆͷΧϥϜʹ͋Δ஋͔͠ ೖྗͰ͖ͳ͍Α͏ʹ͢Δػೳ

  25. Α͘࢖͏ͷ͸தؒςʔϒϧ ϑΥϩʔɾϑΥϩϫʔΈ͍ͨͳؔ࿈෇͚Ͱ ଘࡏ͠ͳ͍ϢʔβʔΛϑΥϩʔͰ͖ͳ͍Α͏ʹ͢Δ

  26. None
  27. class CreateRelationships < ActiveRecord::Migration[5.2] def change create_table :relationships do |t|

    t.references :user, foreign_key: true, null: false t.references :followed, foreign_key: { to_table: :users }, null: false t.timestamps end end end
  28. ΧϥϜ໊ͱࢀরઌͷ໊લ͕ಉ͡ foreign_key: true ҧ͏৔߹ foreign_key: { to_table: :ςʔϒϧ໊ }

  29. DBͷ੔߹ੑΛอͭ࠷ޙͷࡆ = ੍໿

  30. ੍໿͸ͪΌΜͱ࢖͍·͠ΐ͏

  31. 3.ΞϓϦέʔγϣϯ͋Γ͖ͰDBΛߟ͑ͳ͍

  32. Railsͷಛ௃ ςʔϒϧ = Ϋϥε

  33. ςʔϒϧઃܭͱ࣮૷Λಉ࣌ʹߟ͕͑ͪ

  34. ҰͭͷΞΧ΢ϯτʹෳ਺ͷϩʔϧ͕͋Δ ྫ.ചΓखͱങ͍ख

  35. None
  36. class User < ApplicationRecord # ڞ௨ͷ৘ใ end class Seller <

    ApplicationRecord has_many :selling_items, dependent: :destroy ɹ# ചΓखʹؔ͢ΔϦϨʔγϣϯ # ചΓखʹؔ͢ΔϏδωεϩδοΫ end class Buyer < ApplicationRecord # ങ͍खʹؔ͢ΔϦϨʔγϣϯ # ങ͍खʹؔ͢ΔϏδωεϩδοΫ end
  37. ໨త ϦϨʔγϣϯͱϏδωεϩδοΫͷ෼ׂ ↓ ςʔϒϧ࡞Δͷ͸৑௕

  38. None
  39. class User < ApplicationRecord # ڞ௨ͷ৘ใ end class Seller <

    User has_many :selling_items, dependent: :destroy ɹ# ചΓखʹؔ͢ΔϦϨʔγϣϯ # ചΓखʹؔ͢ΔϏδωεϩδοΫ end class Buyer < User # ങ͍खʹؔ͢ΔϦϨʔγϣϯ # ങ͍खʹؔ͢ΔϏδωεϩδοΫ end
  40. Ϋϥεͱͯ͠ඞཁ ≠ ςʔϒϧ࡞Δ

  41. ݴΘΕΔͱ౰વͳΜ͚ͩͲ ҰਓͰ΍ͬͯΔͱҊ֎ϛε͍ͬͯΔ

  42. ·ͱΊ

  43. ·ͱΊ • ΞϓϦέʔγϣϯͷϑϨʔϜϫʔΫ͕มΘΔ͜ͱ͸͋ͬͯ΋ σʔλϕʔε͕·ΔͬͱมΘΔ͜ͱ͸ͳ͔ͳ͔ͳ͍ɻ • ͔ͩΒͦ͜ɺσʔλϕʔε͸ઃܭͳͲΛ͓Ζ͔ͦʹͤͣɺͪΌ Μͱ஌Δඞཁ͕͋Δɻ • ͨͩɺઃܭ͸ҰਓͰ΍ͬͯΔͱ͍ͭͷؒʹ͔ϋϚͬͯͨΓਏ͍ ͷͰɺڧ͍ਓͱҰॹʹͱ͔ɺଟਓ਺Ͱ΍ͬͨ΄͏͕Αͦ͞͏ɻ