Commit cb068077017e5d664fe413048dfcfcb102efb44f
Committed by
Braulio Bhavamitra
1 parent
8923158b
Exists in
master
and in
29 other branches
Speed up build_ancestry
Showing
1 changed file
with
19 additions
and
7 deletions
Show diff stats
lib/acts_as_filesystem.rb
@@ -30,13 +30,17 @@ module ActsAsFileSystem | @@ -30,13 +30,17 @@ module ActsAsFileSystem | ||
30 | module ClassMethods | 30 | module ClassMethods |
31 | 31 | ||
32 | def build_ancestry(parent_id = nil, ancestry = '') | 32 | def build_ancestry(parent_id = nil, ancestry = '') |
33 | - self.base_class.all(:conditions => {:parent_id => parent_id}).each do |node| | ||
34 | - node.ancestry = ancestry | ||
35 | - node.save :run_callbacks => false | 33 | + ActiveRecord::Base.transaction do |
34 | + self.base_class.all(:conditions => {:parent_id => parent_id}).each do |node| | ||
35 | + node.ancestry = ancestry | ||
36 | + node.save :run_callbacks => false | ||
36 | 37 | ||
37 | - build_ancestry node.id, (ancestry.empty? ? "#{node.formatted_ancestry_id}" : | ||
38 | - "#{ancestry}#{node.ancestry_sep}#{node.formatted_ancestry_id}") | 38 | + build_ancestry node.id, (ancestry.empty? ? "#{node.formatted_ancestry_id}" : |
39 | + "#{ancestry}#{node.ancestry_sep}#{node.formatted_ancestry_id}") | ||
40 | + end | ||
39 | end | 41 | end |
42 | + | ||
43 | + #raise "Couldn't reach and set ancestry on every record" if self.base_class.count(:conditions => ['ancestry is null']) != 0 | ||
40 | end | 44 | end |
41 | 45 | ||
42 | end | 46 | end |
@@ -129,10 +133,18 @@ module ActsAsFileSystem | @@ -129,10 +133,18 @@ module ActsAsFileSystem | ||
129 | end | 133 | end |
130 | 134 | ||
131 | def top_ancestor | 135 | def top_ancestor |
132 | - self.hierarchy.first | 136 | + if has_ancestry? and !ancestry.nil? |
137 | + self.class.base_class.find_by_id self.top_ancestor_id | ||
138 | + else | ||
139 | + self.hierarchy.first | ||
140 | + end | ||
133 | end | 141 | end |
134 | def top_ancestor_id | 142 | def top_ancestor_id |
135 | - self.ancestor_ids.first | 143 | + if has_ancestry? and !ancestry.nil? |
144 | + self.ancestor_ids.first | ||
145 | + else | ||
146 | + self.hierarchy.first.id | ||
147 | + end | ||
136 | end | 148 | end |
137 | 149 | ||
138 | # returns the full hierarchy from the top-level item to this one. For | 150 | # returns the full hierarchy from the top-level item to this one. For |