Hi. Ancestry provides scopes like "ancestors_of, subtree_of", etc. But these scopes are Class ones, and can not be chained to other scopes.
For instance, if i have "scope :open, :conditions => 'open = 1'", i cannot chain it with Ancestry scopes like : "Model.open.subtree".
Is there a way to perform such operation?
I have a scope like this : named_scope :open, :conditions => "brand is not null", and i would like to select all models that are subtree of this scope.
Currently, i have to build a loop and selecting all subtrees of each model ; that is not efficient at all (n requests rather than 1).
I found an other solution, that is not perfect since its not really chainable, and looks like this :
named_scope :branded, lambda {{
:joins => "LEFT JOIN groups AS ancestors ON (
groups.ancestry = ancestors.id
OR groups.ancestry LIKE CONCAT(ancestors.id,'/%')
OR groups.ancestry LIKE CONCAT('%/', CONCAT(ancestors.id,'/%'))
OR groups.ancestry LIKE CONCAT('%/',ancestors.id)
OR ancestors.id = groups.id
)",
:conditions => '(ancestors.brand IS NOT NULL AND ancestors.brand !="")'
}}
LTREE
by using ltree2text
when LTREE
is used instead of a string column, but that would only slow performance. Adding full support for LTREE
could be done as well, but would require some more work. Feel free to create a pull-request if you are up for it.
Hello guys, could you help me with some question, when i setup ancestry for my model Category and create 4 items wich includes each other, last item has depth 2, but it shuld be 4 http://prntscr.com/br8hww
A - 1
B - 2
C - 2 (should be 3)
D - 2 (should be 4)
/1/3/5/
(with leading and trailing slashes)
try_two.parent = try_one
try_two.save!
assert_equal try_one.children.first, try_two
subtree.arrange
, then walking it...def print_objs(subtree, indent = '')
subtree = subtree.sort_by { |rec, _children| rec.name }
subtree.each do |rec, children|
puts "#{indent}- #{rec.name} (#{rec.id})"
print_objs(children, " #{indent}")
end
end
roots = Model.roots.sort_by(&:name)
roots.each do |root|
print_objs(root.subtree.arrange)
puts("\n")
end