2016-11-07 61 views
0

我有一個表單,登錄的用戶可以向帖子添加評論。表單發送到comments_controller提交驗證錯誤時發生N + 1查詢

# controllers/comments_controller.rb 
def create 
    @post = Post.find(params[:post_id]) 

    @comment = @post.comments.create(params[:comment].permit(:body).merge(:user => current_user)) 

    if @comment.errors.any? 
     render "posts/show" 
    else 
     redirect_to post_path(@post) 
    end 

    # have also tried this way too 
    # @comment = @post.comments.build(params[:comment].permit(:body)) 
    # @comment.user = current_user 
    # if @comment.save 
    # redirect_to post_path(@post) 
    # else 
    # render "posts/show" 
    # end 
end 

# views/posts/show.html.haml 
%h3 This post has #{ pluralize(@post.comments.count, "comment") } 
= render @post.comments # views/comments/_comment.html.haml 
= render "comments/form" 

# views/comments/_comment.html.haml - list all comments of the post 
- if comment && comment.created_at.present? 
    .media 
    .media-body 
     %h4.media-heading 
     = comment.user.name 
     %small added #{time_ago_in_words comment.created_at} ago 
     %p= comment.body 
    %hr 

comment.body爲必填字段。

如果我試圖向沒有評論的帖子提交一個空表單,這個工作正常,"posts/show"視圖呈現與預期的驗證錯誤。現在,如果我在已經包含一些評論的帖子中再次重複相同的步驟,我會收到N + 1查詢正在運行的警告。這是什麼來自Bullet寶石:

N+1 Query detected 
    Comment => [:user] 
    Add to your finder: :includes => [:user] 
N+1 Query method call stack 
    /app/views/comments/_comment.html.haml:5:in `_app_views_comments__comment_html_haml__3499194119219243109_33739760' 
    /app/views/posts/show.html.haml:23:in `_app_views_posts_show_html_haml__2205508389884571191_36379560' 
    /app/controllers/comments_controller.rb:10:in `create' 

/app/views/comments/_comment.html.haml:5:in `_app_views_comments__comment_html_haml__3499194119219243109_33739760' 
/app/views/posts/show.html.haml:23:in `_app_views_posts_show_html_haml__2205508389884571191_36379560' 
/app/controllers/comments_controller.rb:10:in `create' 

我該如何解決這個問題?

+0

你有什麼在你的'_comment.html.haml'部分? – fanta

+0

我做了一個更新 – Lykos

+1

我明白了,所以,你需要加載你的'comments'和'commens'用戶'來避免這個錯誤。用'Post.includes(comments :: user).find(params [:post_id])試試' – fanta

回答

0

你需要的是告訴軌加載postcommentscommentsuser這樣的:

Post.includes(comments: :user).find(params[:post_id]) 
+0

再次感謝您的幫助! :-) – Lykos