Module: CollectiveIdea::Acts::NestedSet::Depth

Defined in:
lib/nested_set/depth.rb

Instance Method Summary collapse

Instance Method Details

#has_depth_column?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/nested_set/depth.rb', line 18

def has_depth_column?
  respond_to?(depth_column_name)
end

#scope_condition(table_name = nil) ⇒ Object

Model scope conditions



7
8
9
10
11
12
13
14
15
# File 'lib/nested_set/depth.rb', line 7

def scope_condition(table_name=nil)
  table_name ||= self.class.quoted_table_name

  scope_string = Array(acts_as_nested_set_options[:scope]).map do |c|
    "#{table_name}.#{connection.quote_column_name(c)} = #{self.send(c)}"
  end.join(" AND ")

  scope_string.blank? ? "1 = 1" : scope_string
end

#update_all_depthObject

Update cached_level attribute for all record tree



35
36
37
38
39
40
41
42
43
44
# File 'lib/nested_set/depth.rb', line 35

def update_all_depth
  if has_depth_column?
    self.class.connection.execute("UPDATE #{self.class.quoted_table_name} a SET a.#{self.class.quoted_depth_column_name} = \
        (SELECT count(*) - 1 FROM (SELECT * FROM #{self.class.quoted_table_name} WHERE #{scope_condition}) AS b \
      	WHERE #{scope_condition('a')} AND \
      	(a.#{quoted_left_column_name} BETWEEN b.#{quoted_left_column_name} AND b.#{quoted_right_column_name}))
      	WHERE #{scope_condition('a')}
      ")
  end
end

#update_depthObject

Update cached_level attribute



23
24
25
26
27
28
29
30
31
32
# File 'lib/nested_set/depth.rb', line 23

def update_depth
  send :"#{depth_column_name}=", level
  depth_changed = send :"#{depth_column_name}_changed?"
  if depth_changed
    depth_change = send :"#{depth_column_name}_change"
    self.self_and_descendants.
      update_all(["#{self.class.quoted_depth_column_name} = COALESCE(#{self.class.quoted_depth_column_name}, 0) + ?",
        depth_change[1] - depth_change[0].to_i])
  end
end