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使得它失敗了,我不知道爲什麼。也許這與樹的再平衡有關?