0

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

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • 1
    There seems to be some verbage relating to levels here: http://rubydoc.info/gems/nested_set/1.6.4/frames Have you tried using `each_with_level`? – Steve Feb 18 '11 at 21:31
  • @Steve, thanks but I'm not sure that fits the bill here. I think each_with_level is for looping over results. Where what I am dealing with is inserting a new nested object, and wanting to prevent a level from being set to deep. Right? – AnApprentice Feb 18 '11 at 21:34

1 Answers1

1

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?

zetetic
  • 47,184
  • 10
  • 111
  • 119
  • Strange, before_save doesn't fail for me. But what does fail is IF LEVEL or if self.level (all lowercase), always returns 0 – AnApprentice Feb 19 '11 at 02:22
  • Looks like it's because acts_as_nested_set runs after save? A logger output of the comment object before_save shows: parent_id: 251, lft: nil, rgt: nil – AnApprentice Feb 19 '11 at 02:25