I have a simple rails app that displays a single page where one can post comments and reply to those comments and on and on.
The model for comments is quite simple:
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
And, the controller, will pass to view only the root level comments:
def index
@root_comments = Comment.where('parent_id IS NULL')
end
Finally the view will fetch the reply comments of the root comments and render everything:
<% @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 %>
So far so good... Until check the rails server output and...
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 queries everywhere...
I haven't found anything about a inbuilt rails server optimization to manage this kind of approach so.
1) Anyone knows if such optimization exists?
2) If it does not exist how can I fix this issue?
I have tried to eager loading the contacts in the controller but the server output shows the same number of queries.
@root_comments = Comment.includes(:replies).where('parent_id IS NULL')
Thanks!