无法获取要在视图文件中显示的历史注释

时间:2014-09-10 20:33:48

标签: ruby-on-rails

我正在尝试将评论表单添加到博客帖子中,并显示历史评论。我创造了两个部分。我可以在posts / show视图中看到评论表单,我可以留下评论,并将评论添加到数据库中,但那些评论是 未显示

如何才能显示这些历史评论?

以下是我的相关文件/摘录:

应用程序/视图/帖/ show.html.erb

<%= render partial: '/comments/comment', locals: { comments: @comments}  %> 

<%= render partial: '/comments/form', locals: { comment: @comment } %>

应用程序/视图/评论/ _comment.html.erb

<% comments.each do |comment| %>
  <%= comment.body + " " + comment.user.name %>
<% end %>
    

应用程序/视图/评论/ _form.html.erb

<%= form_for [@post, comment] do |f| %> 
  <%= f.label :body %>
  <%= f.text_area :body %>

  <%= f.submit "Save" %>
<% end %>

应用程序/控制器/ posts_controller.rb

def show
  @topic = Topic.find(params[:topic_id])
  @post = Post.find(params[:id])
  @comments = @post.comments
  @comment = Comment.new
end

应用程序/控制器/ comments_controller.rb

def create
  @post = Post.find(params[:post_id])
  @topic = @post.topic
  @comment = current_user.comments.new(comment_params)
  @comment.post = @post
  if @comment.save
    redirect_to [@topic, @post], notice: "Comment was saved successfully."
  else
    flash[:error] = "Error creating comment.  Please try again."
    render :new
  end 
end

感谢。

1 个答案:

答案 0 :(得分:0)

据我所知,如果您确定正确创建了评论(并与正确的帖子相关联),那么主要有两种可能:

  1. 渲染局部的方式有问题。惯例是取消前导/,我认为它可能导致错误的路径(所以comments/comment)。也就是说,我认为如果找不到文件就会引发错误,而不是保持沉默。

  2. 隐藏部分的某种样式或条件逻辑。周围有条件可能是假的吗?出于任何原因有display: none的任何内容吗?

  3. @comments变量可以不正确地实例化,但对我来说这看起来很合理。您只需将此行添加到节目视图的顶部,然后查看打印内容即可对其进行测试:

    <%= @comments %>

    如果打印了一堆评论,那么我会把那条线拿出来,看看当你在局部内部添加<%= comments %>时会发生什么。缩小问题范围,直到看到它的位置 - 因为当我查看它时,上面的代码对我来说很好。