【发布时间】:2016-11-07 09:59:04
【问题描述】:
我有一个表单,登录用户可以在其中将 cmets 添加到帖子中。到目前为止,这是我文件中的代码:
# 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
当我单击提交按钮以添加表单为空的评论时(需要评论正文),我收到了这个奇怪的错误(更好的错误 gem)
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 的代码,一切正常 - 除了我没有得到 cmets 列表这一事实 - 验证按预期工作,我可以在我的屏幕上看到错误.
我该如何解决这个问题?
编辑
工作正常,但我还在为一件事而苦苦挣扎。如果帖子已经有一些旧的 cmets,我会收到 N+1 Queries running 的警告。
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) ??
【问题讨论】:
标签: ruby-on-rails validation ruby-on-rails-4