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

Rubyで階層構造

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for ryonext ryonext
February 20, 2013

 Rubyで階層構造

Rubyで階層構造を実現するancestryというgemの話

Avatar for ryonext

ryonext

February 20, 2013
Tweet

More Decks by ryonext

Other Decks in Programming

Transcript

  1. 親IDだけもつような構造、良くな い • Comments • id • parent_id • comment

    • のような設計 • => 深さがどれぐらいになるかわからない し、再起処理でDQNクエリが走る
  2. 使い方通りに以下の様なデータを • rails g model group name • Create migration:

    rails g migration add_ancestry_to_group ancestry:string • Add index to migration: add_index gruop, :ancestry (UP) / remove_index gruop, :ancestry (DOWN) • Migrate your database: rake db:migrate • Add to app/models/gruop.rb: has_ancestry
  3. こんなデータ作ってみた • 宇宙 • 銀河系 – 太陽系 • 水 •

    金 • 地 – 日本 • 関東 • 東京 • 渋谷 • 浅草 • グンマー – アメリカ – イギリス • 火 • 木 • 土 • 天 • 海 • その他 – 冥ちゃん・・・(´;ω;`)
  4. ここで子孫全部取る処理 • 宇宙 < 僕の子孫あつまれー(^o^)ノ • 銀河系 – 太陽系 •

    水 • 金 • 地 – 日本 • 関東 • 東京 • 渋谷 • 浅草 • グンマー – アメリカ – イギリス • 火 • 木 • 土 • 天 • 海 • その他 – 冥ちゃん・・・(´;ω;`)
  5. クエリが一個しか発行されない • Group.find_by_name("宇宙").descendants • Group Load (0.4ms) SELECT "groups".* FROM

    "groups" WHERE (groups.ancestry like '1/%' or groups.ancestry = '1') • => どの階層でやっても応答速度が同一