我有一个简单的rails应用程序,它显示一个页面,可以发布评论并回复这些评论。
评论模型非常简单:
class Comment < ActiveRecord::Base
attr_accessible :text, :parent_id
attr_accessor :level
has_many :replies, :class_name => 'Comment', :foreign_key => 'parent_id'
belongs_to :parent, :class_name => 'Comment'
scope :get_replies, where(parent_id: to_param})
end
并且,控制器将仅传递以查看根级别注释:
def index
@root_comments = Comment.where('parent_id IS NULL')
end
最后,视图将获取根评论的回复评论并呈现所有内容:
<% @root_comments.each{ |c| c.level = 0} %>
<% while @root_comments.size > 0 %>
<% comment = @root_comments[0] %>
<% @root_comments.delete_at(0) %>
<% replies = comment.get_replies %>
<% replies.each{ |r| r.level = comment.level + 1} %>
<% @root_comments = replies + @root_comments %>
<div class="comment" style=<%= "margin-left:#{(comment.level * 50)}px;" %> >
<%= comment.text %>
</div>
<% end %>
到目前为止一直这么好......直到检查rails服务器输出和......
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE (parent_id IS NULL)
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."parent_id" = 1
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."parent_id" = 4
...
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."parent_id" = 16
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."parent_id" = 17
无处不在的SQL查询......
我没有找到任何有关内置rails服务器优化的内容来管理这种方法。
1)任何人都知道这种优化是否存在?
2)如果不存在,我该如何解决这个问题?
我曾试图加载控制器中的联系人,但服务器输出显示相同数量的查询。
@root_comments = Comment.includes(:replies).where('parent_id IS NULL')
谢谢!
答案 0 :(得分:2)
您可以做的一件事是将评论与每条评论存储在一起,这样您就可以使用两个查询查询所有评论:
* where('parent_id IS NULL')#将这些的id提取到root_ids中
* where('root_id IN?',root_ids)
缺点是您必须在代码中重建树。
答案 1 :(得分:1)
你应该看看rails eager loading。试试
def index
@root_comments = Comment.includes(:comment).where('parent_id IS NULL')
end
答案 2 :(得分:0)