0

我目前正在使用gem'nested_set'进行评论线程化。Rails - 作为嵌套行为 - 实施最高级别

我想要做的是防止评论级别超过2级。我累了做的是这样的:

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 

但它看起来像你不能设置一个级别只获得一个对象级别。目标是强制执行深度为2的MAX级别的注释线程。任何人都可以建议一种方法来强制实施吗?

使用情况下存在:

Comment Main (level 0) 

    Comment Reply (level 1) 

    Comment Reply about XXXX (level 2) 

当用户回复的最后一个(约XXXX)我不想评论将被设置为3的水平,我想帽在2.

想法?谢谢

+1

似乎有一些verbage与这里的关卡有关:http://rubydoc.info/gems/nested_set/1.6.4/frames您是否尝试过使用`each_with_level`? – Steve 2011-02-18 21:31:23

+0

@Steve,谢谢,但我不确定这是否符合法案。我认为each_with_level是用于循环结果。我正在处理的是插入一个新的嵌套对象,并希望防止将级别设置为较深。对? – AnApprentice 2011-02-18 21:34:22

回答

1

这似乎工作,虽然可能有更好的解决方案。

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 

请注意,更改这before_save使得它失败了,我不知道为什么。也许这与树的再平衡有关?