Search code examples
ruby-on-railsruby-on-rails-3nestednested-setsacts-as-tree

Rails - Acts as nested - Enforcing a Max Level


I'm currently using the gem 'nested_set' for comment threading.

What I want to do is prevent the comment level from going more than 2 levels deep. What I tired doing was something like this:

class Comment < ActiveRecord::Base
    ....
    before_save :ensure_max_nestedset_level
  private

    # We don't want comments to go more than 2 levels deep. That's overkill
    def ensure_max_nestedset_level
      if self.level > 2
        self.level = 2
      end
    end

end

But it looks like you cant set a level only obtain an objects level. With the goal being to enforce a MAX of 2 levels deep for comment threading. Can anyone suggest a way to enforce that from happening?

The use case being:

Comment Main (level 0)

  Comment Reply (level 1)

    Comment Reply about XXXX (level 2)

When a user replies to the last one (about XXXX) I don't want the comment to be set to a level of 3, I want to cap that at 2.

Ideas? Thanks


Solution

  • This seems to work, though there might be a better solution.

    class Comment < ActiveRecord::Base
      acts_as_nested_set
    
      after_save :check_level
    
      def check_level
        if level > 2
          move_to_child_of(parent.parent)
        end
      end
    end
    

    Note that changing this to before_save makes it fail, I don't know why. Perhaps it has to do with the rebalancing of the tree?