提交验证错误时发生N + 1个查询

时间:2016-11-07 20:31:17

标签: ruby-on-rails ruby-on-rails-4 rubygems

我有一个表格,登录用户可以在帖子中添加评论。表单发布到comments_controller

# 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 gem:

的内容
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'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要告诉rails加载post的{​​{1}}和comments'comments,如下所示:

user