我使用嵌套set来表示嵌套评论(1个讨论,其中有许多评论,评论可以回复),我希望(如果可能)急于加载评论的答案。
此时,我加载所有根节点并遍历它们,如果它们有子代,我会渲染它们。但是,如果有很多具有答案的根节点,则会触发大量的DB请求。
评论包含以下列:rgt, lft, parent_id
我试着建立这样的关系:
class Comment < ActiveRecord::Base
has_many :answers, -> (node) { where("lft > ? AND rgt < ?", node.lft, node.rgt) }, class_name: "Comment", foreign_key: :parent_id
end当在comment实例上调用时,这将获取评论的答案。但是,如果我尝试eager_load it (Discussion.comments.includes(:answers)),它会失败,因为node为零。
是否有可能立即加载类似这样的内容?
发布于 2015-04-02 03:06:38
我想,我找到了一个解决方案。如果我没看错的话,您的数据模型如下所示:
Discussion
----------
...
Comment
----------
discussion_id:int
parent_id:int
lft:int
rgt:int则AR模型类将为:
class Discussion < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :discussion
end要立即加载讨论(id == 1)及其所有评论和答案树,请使用:
d = Discussion.includes(:comments).find(1)它在内存(d.comments)中给出了给定讨论的所有注释的集合。
现在我们可以操作这个集合来获得任何特定评论的答案,而不需要额外的DB查询。只需将此代码添加到Discussion类:
def comment_roots
self.comments.select {|c| c.parent_id.nil? }
end这是Comment类的代码:
def answers
self.discussion.comments.select {|c| c.parent_id = self.id }
end
def answers_tree
self.discussion.comments.select {|c| self.lft < c.lft && c.rgt < self.rgt }
end示例:
d.comment_roots.first.answershttps://stackoverflow.com/questions/29396150
复制相似问题