ClosureTree / closure_tree

Easily and efficiently make your ActiveRecord models support hierarchies
https://closuretree.github.io/closure_tree/
MIT License
1.83k stars 240 forks source link

Update ancestry_path without record reloading. #145

Open kremen opened 9 years ago

kremen commented 9 years ago

After record attribute updating ancestry_path is out-of-date. It becomes up-to-date after record reloading.

d = Tag.find_or_create_by_path %w[a b c d]
d.update {name: 'new_d'}
d.ancestry_path
=> ["a", "b", "c", "d"]
d.reload
d.ancestry_path
=> ["a", "b", "c", "new_d"]
mceachen commented 9 years ago

ancestry_path uses self_and_ancestors, whose cache management is at the mercy of activerecord—what's frustrating is that activerecord has a bug that prevents the self_and_ancestors from caching a self-reference to d. The d.self_and_ancestors array has a disconnected copy of d.

I could change to

    def ancestry_path(to_s_column = _ct.name_column)
      ancestors.reverse.map { |n| n.send(to_s_column.to_sym) } <<
        send(to_s_column.to_sym)
    end

but that results in the value never being cacheable due to the scoping of ancestors.