SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
イケテル
better nested set
      研究会
   藤岡岳之(xibbar)
アジェンダ




better nested setを使って組織図を書く
手軽に書きたいんだ∼!
Sectionモデルを作成1




better nested setをインストール
Sectionモデルを作成2
migrationファイル
  モデルはSectionという名前にすることにして、使用
  するカラムはnameだけに
  better nested setにはparent_id、lft、rgtとい
  う:integerなカラムが必要
class CreateSections < ActiveRecord::Migration
 def self.up
   create_table :sections do ¦t¦
    t.column :name, :string, :null=>false
    t.column :parent_id, :integer
    t.column :lft,    :integer
    t.column :rgt,      :integer
   end
 end
 def self.down
   drop_table :sections
 end
end
Sectionモデルを作成3

app/models/section.rbの中身


   class Section < ActiveRecord::Base
           acts_as_nested_set
   end
データを作成

              ツリーを作成してみる
%   ./script/runner   'Section.create(:name=>"日本Ruby会議")'
%   ./script/runner   'Section.create(:name=>"東京Ruby会議").move_to_child_of Section.find_by_name("日本Ruby会議")'
%   ./script/runner   'Section.create(:name=>"札幌Ruby会議").move_to_child_of Section.find_by_name("日本Ruby会議")'
%   ./script/runner   'Section.create(:name=>"Akasaka.rb").move_to_child_of Section.find_by_name("東京Ruby会議")'
%   ./script/runner   'Section.create(:name=>"Asakusa.rb").move_to_child_of Section.find_by_name("東京Ruby会議")'




              DBの中身は
                             # select * from sections;
                              id ¦   name       ¦ parent_id ¦ lft ¦ rgt
                             ----+--------------+-----------+-----+-----
                               1 ¦ 日本Ruby会議 ¦                ¦ 1 ¦ 10
                               2 ¦ 東京Ruby会議 ¦              1¦ 2¦ 7
                               3 ¦ 札幌Ruby会議 ¦              1¦ 8¦ 9
                               4 ¦ Akasaka.rb ¦            2¦ 3¦ 4
                               5 ¦ Asakusa.rb ¦            2¦ 5¦ 6
                             (5 rows)
自作プラグインを導入



./script/plugin install http://xibbar.net/svn/
rails/plugins/trunk/acts_as_section_map/
モデルに一行追加


     class Section < ActiveRecord::Base
      acts_as_nested_set
      acts_as_section_map
     end


※ acts_as_section_mapは
  acts_as_nested_setの下に書くこと
コントローラー
                1行追加

class WelcomeController <ApplicationController
 def index
  @table2=Section.table2
 end
end
ビュー
index.rhtml
 <% section_map(@table2) do ¦table¦ %>
  <%=table.name%>
 <% end %>
   ※ テーブルの中身はブロックで指定




    ※ プラグインの魔法で、
    たったこれだけで組織図完成
関連テーブル
    user.rb                                       section.rb
                                              class Section < ActiveRecord::Base
class CreateUsers < ActiveRecord::Migration
                                               acts_as_nested_set
 def self.up
                                               acts_as_section_map
   create_table :users do ¦t¦
                                               has_many :users
    t.column :name, :string, :null=>false
                                              end
    t.column :section_id, :integer
   end
 end
 def self.down
   drop_table :users
 end
end


class User < ActiveRecord::Base
 belongs_to :section
end
データ作成

        userを作成し、sectionにぶら下げる
%   ./script/runner   'Section.find_by_name("Akasaka.rb").users   <<   User.create(:name=>"takai")'
%   ./script/runner   'Section.find_by_name("Akasaka.rb").users   <<   User.create(:name=>"koichiroo")'
%   ./script/runner   'Section.find_by_name("Akasaka.rb").users   <<   User.create(:name=>"takedasoft")'
%   ./script/runner   'Section.find_by_name("Asakusa.rb").users   <<   User.create(:name=>"a_matsuda")'
%   ./script/runner   'Section.find_by_name("Asakusa.rb").users   <<   User.create(:name=>"kakutani")'
%   ./script/runner   'Section.find_by_name("Asakusa.rb").users   <<   User.create(:name=>"maiha")'
ビューも直す
index.rhtml
<% section_map(@table2) do ¦table¦ %>
 <%=table.name%>
 <ul>
 <% table.users.each do ¦user¦%>
  <li><%=user.name%></li>
 <%end%>
 </ul>
<% end %>
見た目を直そう
index.rhtml
<% section_map(@table2,:table=>{:cellspacing=>"0",:style=>"border-collapse:collapse;"},
           :td=>{:valign=>"top",:style=>"border:1px solid #666666;color:navy;"}) do ¦table¦ %>
 <%=table.name%>
 <ul>
 <% table.users.each do ¦user¦%>
  <li style="font-size:12px;color:green"><%=user.name%></li>
 <%end%>
 </ul>
<% end %>
のろくない?



数が多いとのろいぞ
でも、なんとかしちゃる
でも今日はおしまい
続きは次回以降
イケテルDB
  チューニング

xibbarこと藤岡岳之
ブログのぶくま
これでぎりぎり卒論になるんじゃなかろうか。
長谷川がこけたら、これにしようかな。。。



     なんだこれ!!
巨大な組織

(1..4).each{¦n¦Section.create(:name=>"Section:#{n}")}
(5..60).each{¦n¦2.times{¦m¦
Section.find_or_create_by_name("Section:#{n*2+m
+3}").move_to_child_of
Section.find_by_name("Section:#{n}")}}




  120組織のツリーを作るスクリプト
遅すぎる

 User Load (0.000204) SELECT * FROM users
WHERE (users.section_id = 124)
Completed in 18.13171 (0 reqs/sec) ¦ Rendering:
7.49291 (41%) ¦ DB: 10.46457 (57%) ¦ 200 OK
[http://localhost/welcome]


            表示に18秒っておい!
インデックスを張ってみる

 User Load (0.000182) SELECT * FROM users
WHERE (users.section_id = 124)
Completed in 10.01978 (0 reqs/sec) ¦ Rendering:
6.97071 (69%) ¦ DB: 2.87357 (28%) ¦ 200 OK
[http://localhost/welcome]

             10秒に短縮!
          まだ使い物にならないけど
すばやさの種を投入
class AddDepthToSections < ActiveRecord::Migration
 def self.up
   add_column :sections,:depth,:integer
   Section.set_depth
 end


 def self.down
  remove_column :sections,:depth
 end
end


  depthという項目を追加し、
  値をセットする。depthというのは
  文字通り深さの値(levelの結果)
すばやさの種の結果

 User Load (0.000180) SELECT * FROM users WHERE
(users.section_id = 124)
Completed in 0.84391 (1 reqs/sec) ¦ Rendering: 0.40329 (47%) ¦
DB: 0.27316 (32%) ¦ 200 OK [http://localhost/welcome]




         1秒切ってメデタシメデタシ
ちょっとだけ解説



のろさの原因はsectionが自分自身の深さを
知るためにselect count(*)していることに
ある。(levelメソッド)
これをカラムとして持つとツリーの構築の早
さが圧倒的に違う(つまりdepthカラム)
benchmark
% ./script/performance/benchmarker 100 'Section.find(:all).map(&:level)'
        user   system   total   real
#1    5.790000 0.470000 6.260000 ( 10.331682)

% ./script/performance/benchmarker 100 'Section.find(:all).map(&:depth)'
        user   system   total   real
#1    0.610000 0.010000 0.620000 ( 0.784886)


                ちなみにindex張る前は
% ./script/performance/benchmarker 100 'Section.find(:all).map(&:level)'
        user   system   total   real
#1    6.180000 0.530000 6.710000 ( 20.693455)


            20.693 0.784=26.394
                  26倍早くなった!!
グー

おしまい


       http://www001.upp.so-net.ne.jp/masa_gallery/edo.html

Weitere ähnliche Inhalte

Andere mochten auch

Bali bible new testament
Bali bible   new testamentBali bible   new testament
Bali bible new testament
EternalWord
 
Boletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-Andalucía
Boletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-AndalucíaBoletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-Andalucía
Boletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-Andalucía
FEAFES ANDALUCÍA SALUD MENTAL
 
Social Media Strategy by Startup Lifecycle Stage
Social Media Strategy by Startup Lifecycle StageSocial Media Strategy by Startup Lifecycle Stage
Social Media Strategy by Startup Lifecycle Stage
Oliver Moser
 
Netdating opgave
Netdating opgave Netdating opgave
Netdating opgave
Anne Lundov
 
CV of Dr. Stephen J. Cina, Cook County Medical Examiner
CV of Dr. Stephen J. Cina, Cook County Medical ExaminerCV of Dr. Stephen J. Cina, Cook County Medical Examiner
CV of Dr. Stephen J. Cina, Cook County Medical Examiner
cookcountyblog
 

Andere mochten auch (20)

#JovenesTIC28J Participación a través de las TIC. Fundación Esplai
#JovenesTIC28J Participación a través de las TIC. Fundación Esplai#JovenesTIC28J Participación a través de las TIC. Fundación Esplai
#JovenesTIC28J Participación a través de las TIC. Fundación Esplai
 
Social media marketing
Social media marketingSocial media marketing
Social media marketing
 
Minor kick off-03
Minor kick off-03Minor kick off-03
Minor kick off-03
 
Edema agudo pulmonar
Edema agudo pulmonarEdema agudo pulmonar
Edema agudo pulmonar
 
2011 Catalog Email
2011 Catalog Email2011 Catalog Email
2011 Catalog Email
 
Como Citar segun el Manual de estilo APA
Como Citar segun el Manual de estilo APA Como Citar segun el Manual de estilo APA
Como Citar segun el Manual de estilo APA
 
Bali bible new testament
Bali bible   new testamentBali bible   new testament
Bali bible new testament
 
CV Antonio Caba ICCP
CV Antonio Caba ICCPCV Antonio Caba ICCP
CV Antonio Caba ICCP
 
Boletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-Andalucía
Boletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-AndalucíaBoletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-Andalucía
Boletín especial "Día Mundial de la Salud Mental" 2012 de FEAFES-Andalucía
 
Com Para El Dllo
Com Para El DlloCom Para El Dllo
Com Para El Dllo
 
Wykład volumed
Wykład volumedWykład volumed
Wykład volumed
 
Social Media Strategy by Startup Lifecycle Stage
Social Media Strategy by Startup Lifecycle StageSocial Media Strategy by Startup Lifecycle Stage
Social Media Strategy by Startup Lifecycle Stage
 
Netdating opgave
Netdating opgave Netdating opgave
Netdating opgave
 
Congreso Mundial de Parques de la Union Internacional para la Conservacion de...
Congreso Mundial de Parques de la Union Internacional para la Conservacion de...Congreso Mundial de Parques de la Union Internacional para la Conservacion de...
Congreso Mundial de Parques de la Union Internacional para la Conservacion de...
 
Estrategias modernas para las mypes - 30 de enero
Estrategias modernas para las mypes - 30 de eneroEstrategias modernas para las mypes - 30 de enero
Estrategias modernas para las mypes - 30 de enero
 
Yankee Candles
Yankee CandlesYankee Candles
Yankee Candles
 
Prosperando en familia
Prosperando en familiaProsperando en familia
Prosperando en familia
 
Desmontar el cuadro del seat 600
Desmontar el cuadro del seat 600Desmontar el cuadro del seat 600
Desmontar el cuadro del seat 600
 
CV of Dr. Stephen J. Cina, Cook County Medical Examiner
CV of Dr. Stephen J. Cina, Cook County Medical ExaminerCV of Dr. Stephen J. Cina, Cook County Medical Examiner
CV of Dr. Stephen J. Cina, Cook County Medical Examiner
 
[mrktic] Marketing Automático - Dinamiza las conversiones de tus leads
[mrktic] Marketing Automático - Dinamiza las conversiones de tus leads[mrktic] Marketing Automático - Dinamiza las conversiones de tus leads
[mrktic] Marketing Automático - Dinamiza las conversiones de tus leads
 

Ähnlich wie More Better Nested Set

Ruby on Rails Tutorial Chapter8-10
Ruby on Rails Tutorial Chapter8-10Ruby on Rails Tutorial Chapter8-10
Ruby on Rails Tutorial Chapter8-10
Sea Mountain
 
第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)
Masanori Machii
 
Rails初心者レッスン lesson3 3edition
Rails初心者レッスン lesson3 3editionRails初心者レッスン lesson3 3edition
Rails初心者レッスン lesson3 3edition
Satomi Tsujita
 
スマートフォン向けサービスにおけるサーバサイド設計入門
スマートフォン向けサービスにおけるサーバサイド設計入門スマートフォン向けサービスにおけるサーバサイド設計入門
スマートフォン向けサービスにおけるサーバサイド設計入門
Hisashi HATAKEYAMA
 
My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1
Makoto Haruyama
 

Ähnlich wie More Better Nested Set (20)

Ruby on Rails Tutorial Chapter8-10
Ruby on Rails Tutorial Chapter8-10Ruby on Rails Tutorial Chapter8-10
Ruby on Rails Tutorial Chapter8-10
 
React+redux+saga 01
React+redux+saga 01React+redux+saga 01
React+redux+saga 01
 
Rails基礎講座 part.2
Rails基礎講座 part.2Rails基礎講座 part.2
Rails基礎講座 part.2
 
MySQLとPostgreSQLの基本的な実行プラン比較
MySQLとPostgreSQLの基本的な実行プラン比較MySQLとPostgreSQLの基本的な実行プラン比較
MySQLとPostgreSQLの基本的な実行プラン比較
 
第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)
 
Seasarプロジェクト徹底攻略
Seasarプロジェクト徹底攻略Seasarプロジェクト徹底攻略
Seasarプロジェクト徹底攻略
 
Rails初心者レッスン lesson3 3edition
Rails初心者レッスン lesson3 3editionRails初心者レッスン lesson3 3edition
Rails初心者レッスン lesson3 3edition
 
Okinawa.rb 第2回勉強会
Okinawa.rb 第2回勉強会Okinawa.rb 第2回勉強会
Okinawa.rb 第2回勉強会
 
スマートフォン向けサービスにおけるサーバサイド設計入門
スマートフォン向けサービスにおけるサーバサイド設計入門スマートフォン向けサービスにおけるサーバサイド設計入門
スマートフォン向けサービスにおけるサーバサイド設計入門
 
SQLマッピングフレームワーク「Kobati」のはなし
SQLマッピングフレームワーク「Kobati」のはなしSQLマッピングフレームワーク「Kobati」のはなし
SQLマッピングフレームワーク「Kobati」のはなし
 
My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1
 
Tide - SmalltalkでSPA
Tide - SmalltalkでSPATide - SmalltalkでSPA
Tide - SmalltalkでSPA
 
Ruby 2.5
Ruby 2.5Ruby 2.5
Ruby 2.5
 
仕事の手離れを良くする手段としての、静的検査のあるテンプレートエンジン (YATT::Lite talk at 2014 テンプレートエンジンNight)
仕事の手離れを良くする手段としての、静的検査のあるテンプレートエンジン (YATT::Lite talk at 2014 テンプレートエンジンNight)仕事の手離れを良くする手段としての、静的検査のあるテンプレートエンジン (YATT::Lite talk at 2014 テンプレートエンジンNight)
仕事の手離れを良くする手段としての、静的検査のあるテンプレートエンジン (YATT::Lite talk at 2014 テンプレートエンジンNight)
 
jQuery Performance Tips – jQueryにおける高速化 -
jQuery Performance Tips – jQueryにおける高速化 -jQuery Performance Tips – jQueryにおける高速化 -
jQuery Performance Tips – jQueryにおける高速化 -
 
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
 
Scala on Hadoop
Scala on HadoopScala on Hadoop
Scala on Hadoop
 
図とコード例で多分わかる React と flux (工事中)
図とコード例で多分わかる React と flux (工事中)図とコード例で多分わかる React と flux (工事中)
図とコード例で多分わかる React と flux (工事中)
 
Ruby on Rails Tutorial
Ruby on Rails TutorialRuby on Rails Tutorial
Ruby on Rails Tutorial
 
Ruby on Rails Tutorial Chapter5-7
Ruby on Rails Tutorial Chapter5-7Ruby on Rails Tutorial Chapter5-7
Ruby on Rails Tutorial Chapter5-7
 

Mehr von xibbar

Mehr von xibbar (14)

エンジニア志望だったのにRuby社長をしてよかったと思う5つのこと
エンジニア志望だったのにRuby社長をしてよかったと思う5つのことエンジニア志望だったのにRuby社長をしてよかったと思う5つのこと
エンジニア志望だったのにRuby社長をしてよかったと思う5つのこと
 
札幌Ruby会議03のlt
札幌Ruby会議03のlt札幌Ruby会議03のlt
札幌Ruby会議03のlt
 
Fukushima.rb#00
Fukushima.rb#00Fukushima.rb#00
Fukushima.rb#00
 
仙台Ruby会議02 Pdf
仙台Ruby会議02 Pdf仙台Ruby会議02 Pdf
仙台Ruby会議02 Pdf
 
地域振興論2009
地域振興論2009地域振興論2009
地域振興論2009
 
栃木Ruby会議02 Lt途中まで
栃木Ruby会議02 Lt途中まで栃木Ruby会議02 Lt途中まで
栃木Ruby会議02 Lt途中まで
 
tDiaryなどのレガシーウェブアプリをRuby1.9で動かす方法
tDiaryなどのレガシーウェブアプリをRuby1.9で動かす方法tDiaryなどのレガシーウェブアプリをRuby1.9で動かす方法
tDiaryなどのレガシーウェブアプリをRuby1.9で動かす方法
 
1000speakers仙台
1000speakers仙台1000speakers仙台
1000speakers仙台
 
Ruby&Active Support for expert 3
Ruby&Active Support for expert 3Ruby&Active Support for expert 3
Ruby&Active Support for expert 3
 
RubyとActive Support for expert 2
RubyとActive Support for expert 2RubyとActive Support for expert 2
RubyとActive Support for expert 2
 
Ruby and ActiveSupport for expart
Ruby and ActiveSupport for expartRuby and ActiveSupport for expart
Ruby and ActiveSupport for expart
 
Tohoku Open Source Conference 2008
Tohoku Open Source Conference 2008Tohoku Open Source Conference 2008
Tohoku Open Source Conference 2008
 
acts_asを使ってみよう
acts_asを使ってみようacts_asを使ってみよう
acts_asを使ってみよう
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Pr
 

Kürzlich hochgeladen

Kürzlich hochgeladen (10)

知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx
知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx
知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx
 
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
 
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
 
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
LoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイスLoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイス
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
 
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアルLoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
 
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
 
新人研修 後半 2024/04/26の勉強会で発表されたものです。
新人研修 後半        2024/04/26の勉強会で発表されたものです。新人研修 後半        2024/04/26の勉強会で発表されたものです。
新人研修 後半 2024/04/26の勉強会で発表されたものです。
 
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
 
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
 
Utilizing Ballerina for Cloud Native Integrations
Utilizing Ballerina for Cloud Native IntegrationsUtilizing Ballerina for Cloud Native Integrations
Utilizing Ballerina for Cloud Native Integrations
 

More Better Nested Set