Ruby on rails 停止在@comments-Rails的显示页面上显示新的@comment for comment表单

Ruby on rails 停止在@comments-Rails的显示页面上显示新的@comment for comment表单,ruby-on-rails,ruby,comments,polymorphic-associations,Ruby On Rails,Ruby,Comments,Polymorphic Associations,您好,我是Rails的新手,正在为我的Shop_Profile模型建立评论。我正在使用acts_as_可评论gem来允许多态评论。我允许在个人资料显示页面上发表评论,因此我在同一页面上显示评论列表和新的评论表单 我在ShopProfilesController中的显示操作如下所示: def show @comments = @shop_profile.comments @comment = @shop_profile.comments.new end 我将在show视图中呈

您好,我是Rails的新手,正在为我的Shop_Profile模型建立评论。我正在使用acts_as_可评论gem来允许多态评论。我允许在个人资料显示页面上发表评论,因此我在同一页面上显示评论列表和新的评论表单

我在ShopProfilesController中的显示操作如下所示:

def show
    @comments = @shop_profile.comments
    @comment = @shop_profile.comments.new
  end
我将在show视图中呈现注释表单和注释,其中包含:

<% if user_signed_in? %>
    <%= render 'comments/form' %>
<% end %>

<%= render @comments %>
我的部分评论是:

<p>
  <strong>Title:</strong>
  <%= comment.title %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.comment %>
</p>

<p>
  <small>By:</small>
  <%= comment.user.username %>
</p>

标题:

评论:

作者:

表单的新@comment一直包含在@comments中,因此导致了一个错误“nil:NilClass的未定义方法`username'”,因为新@commentn没有用户id。 我如何显示我的@comments,而不将此新@comments包含在表单_中


感谢您的帮助

您正在收藏中创建一条附加注释,而该新注释还没有关联的用户,也没有保存在数据库中

如果希望完全跳过新注释,可以执行以下操作:

<%= render @comments.reject{|c| c == @comment } %>
<% if comment != @comment %>
  <p>
    <small>By:</small>
    <%= comment.user.username %>
 </p>
<% end %>

如果希望显示新注释,但跳过“By”部分,可以执行以下操作:

<%= render @comments.reject{|c| c == @comment } %>
<% if comment != @comment %>
  <p>
    <small>By:</small>
    <%= comment.user.username %>
 </p>
<% end %>


作者:

不幸的是(在本例中)
new
/
build
将生成的对象添加到关联的集合中。因此,您需要声明您的意图,即只希望数据库中存储
@comments
集合的项目

我知道你有两个选择:

def show
  @comment = @shop_profile.comments.new
  @comments = @shop_profile.comments(true)
end
这将强制干净地加载
@comments
,因此它将只包含原始列表。不幸的是,为了同一个列表,您两次访问数据库,这很愚蠢

我认为,这样做更好:

def show
  @comments = @shop_profile.comments.to_a
  @comment = @shop_profile.comments.new
end

因此,现在您可以将
@comments
集合从活动记录关联中分离出来,使其成为一个数组,这样以后的
new
调用将不会修改您仍然保留的任何内容。

不清楚为什么
@comments
变量会被未保存的数据污染,这是您真正的问题。不要通过在列表中接受坏数据来隐藏它。是否需要
用户id
?你确定
纹身
数据库中保存的记录中没有空的
用户id
?很抱歉,我刚刚将“@comment”变量更正为正确的“@shop\u profile”,我认为是新的“@comment”变量导致了问题,数据库中没有空用户id保存的注释,现在有道理了,看看我的答案。嗨,谢谢你的建议。这是可行的,但是在数据库中不应该有注释包含user_id:nil的情况,所以我认为可能有一种更干净的方法来阻止表单的新注释被包含在comments.all中,并导致我看到的错误。是的,我会补充更多。谢谢,这是一个很好的解决方案,非常简单,有很好的解释。使用.to_解决方案有什么缺点吗?不应该有,除非您稍后在视图中使用ActiveRecord关联方法。