lib/customize/inherited.rb in customize-0.0.6 vs lib/customize/inherited.rb in customize-0.0.7
- old
+ new
@@ -44,20 +44,24 @@
module ClassMethods
def root
joins(:inherit_node).where("parent_id is null")
end
- def type_tree
+ def type_tree node = nil
roots = root
- converter = proc {|items|
- out = items.collect { |item|
- {:id=>item.id,:label=>item.label,:inherit_node_id=>item.inherit_node.id, :children=>converter.call(item.children)}
+ converter = proc {|items, node|
+ out = items.select { |item|
+ node.nil? || (item.inherit_node.id != node.id &&
+ (node.parent_node.nil? || item.inherit_node.id != node.parent_node.id))
+ }.collect { |item|
+ {:id=>item.id,:label=>item.label,:inherit_node_id=>item.inherit_node.id, :children=>converter.call(item.children, node)}
}
}
- converter.call(roots)
+ converter.call(roots, node)
end
+
end
def parent
inherit_node.parent_node.try(:node)
end
@@ -72,10 +76,12 @@
def inherit parent
raise 'should be save first' if self.new_record?
raise 'should be same class' if self.class != parent.class
raise 'should not be self' if self.id == parent.id
+ raise 'should not inherit descents' if self.descent_ids.include? parent.id
+ raise 'should not inherit parent' if self.parent.try(:id) == parent.id
self.class.transaction do
inherit_node.parent_id = parent.inherit_node.id
right = parent.inherit_node.right
InheritNode.where("right >= ?", inherit_node.left).update_all("right = right+2")
inherit_node.left = right
@@ -88,13 +94,13 @@
return [] if new_record?
self.class.ascents_for self, options
end
def inherit_association name, options={:include=>false}
- association_table_name = association(name).aliased_table_name
-
- r = ascents(options).joins(name).select("#{association_table_name}.*").uniq
- r.map(&name).flatten
+ a = association(name)
+ sql = ascents(options).joins(name).select("#{a.aliased_table_name}.#{a.klass.primary_key}").to_sql
+ a.klass.from("(#{sql}) as subquery, #{a.klass.table_name}").
+ where("#{a.klass.table_name}.#{a.klass.primary_key} = subquery.#{a.klass.primary_key}")
end
def descents
return [] if new_record?
self.class.descents_for self