collectiveidea/awesome_nested_set

Model.rebuild! does not rebuild depth

Closed this issue · 6 comments

When executing rebuild! to convert an existing tree (from a previous version that did not support depth), the depth field is not completed automatically.

valid? should also check that this field is correct if it is present.

We are currently using the following monkeypatch for solving the issue.

  def self.rebuild!
    items = self.where(:parent_id => nil)
    level = 0
    while items.any?
      items.update_all :depth => level
      items = self.where(:parent_id => items.map(&:id))
      level += 1
    end
    super
  end

Yes, I've been noticing this too.. It seems the depth only gets built when you run save or move_to commands.

Also had to use monkeypatch.

We've noticed this on a fairly content heavy site (~680 pages) using RefineryCMS with dozen editors who just love to reorder the pages. Rebuild! takes a fair amount of time (~15 min), so any lighter option would be nice.

Here's a more efficient monkeypatch. I've only tested it on PostgreSQL, but it should be standard SQL.

def self.rebuild!
  super
  self.update_all("#{depth_column_name} = ((select count(*) from #{self.quoted_table_name} t where t.lft <= #{self.quoted_table_name}.lft and t.rgt >= #{self.quoted_table_name}.rgt) - 1)")
end

@masonjm got this on mysql :( You can't specify target table 'category_parts' for update in FROM clause

stale commented

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.