Rails - 充当嵌套 - 强制执行最大级别

发布于 2024-10-17 20:55:13 字数 667 浏览 0 评论 0原文

我目前正在使用 gem 'nested_set' 进行评论线程。

我想要做的是防止评论级别深度超过 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 级。谁能建议一种方法来强制这种情况发生?

用例是:

Comment Main (level 0)

  Comment Reply (level 1)

    Comment Reply about XXXX (level 2)

当用户回复最后一条(大约 XXXX)时,我不希望将评论设置为 3 级,我想将其上限设置为 2。

有想法吗?谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如果没有你 2024-10-24 20:55:13

这似乎可行,尽管可能有更好的解决方案。

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 会导致失败,我不知道为什么。也许这与树的重新平衡有关?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文