我有一个登录用户可以向帖子添加评论的表单。这是我在我的文件中的代码,到目前为止:如果验证失败,则为评论显示错误
# 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
.media
.media-body
%h4.media-heading
= comment.user.name
%small added #{time_ago_in_words comment.created_at} ago
%p= comment.body
%hr
# views/comments/_form.html.haml
- if user_signed_in?
= errors_for @comment if @comment # errors_for is just a custom helper I've created to loop through all validation errors
= form_for([@post, Comment.new]) do |f|
.form-group
= f.label :body, "Leave a comment"
= f.text_area :body, class: "form-control", rows: "6"
.form-group
= f.submit "Add", class: "btn btn-primary"
# 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
当我点击提交按钮来添加与形式是空的(需要注释的身体),我得到这个奇怪的错误评论(更好的错误宝石)
NoMethodError at /posts/1/comments
undefined method `>' for nil:NilClass
和特色_comment.html.haml
这行代码%small added #{time_ago_in_words comment.created_at} ago
。另外,如预期的那样,将postID和userID分配给@comment,并且comment.body和created_at和updated_at是预期的。
我已经暂时从这个文件中删除了所有ruby嵌入代码,并且一切正常 - 除了从我没有得到评论列表的事实 - 验证按预期工作,我可以看到我的错误屏幕。
我该如何解决这个问题?
编辑
工作正常,但是我在同一件事情挣扎。如果帖子已经有一些旧评论,我会收到N + 1查询正在运行的警告。
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'
我知道这是脱离主题,但任何想法如何解决这个问题?我在哪里需要使用.includes(:user)
??
感谢,似乎这样的工作方式,但是我有N + 1查询问题,其中有老的意见后submiting形式挣扎时。我怎样才能解决这个问题?请检查我的代码,我做了更新 – Lykos
嗯我不知道那一个 - 我没有太多的n + 1问题的经验。如果你将问题恢复到原来的状态,并提出一个新的问题,那会更好。我相信还有很多其他人在我的n + 1问题上有更多的经验。 – David
好吧,我可能会为此创建一个新主题。再次感谢您的帮助! :-) – Lykos