Rails 显示不存在的数据库记录

Rails shows non existent database records

Rails 表明 Comment 模型的一个实例存在,即使数据库是空的。我显示 Comment 的代码是

<% @post.comments.each do |c| %>
   <%= c %>
<% end %>

然后,如果我这样做,我也会得到 #<Comment:0x007fe971c02800> c.attributes 我得到 {"id"=>nil, "body"=>nil, "author"=>nil, "post_id"=>37, "deleted"=>nil, "locked"=>nil, "created_at"=>nil, "updated_at"=>nil},但是table没有记录。如果我将该代码更改为

<% @post.comments.each do |c| %>
   <%= c.body %>
<% end %>

我一无所获。 也许使用 closure_tree 对我有帮助。 如果有帮助,这里是 table:

的架构
create_table "comment_hierarchies", id: false, force: true do |t|
  t.integer "ancestor_id",   null: false
  t.integer "descendant_id", null: false
  t.integer "generations",   null: false
end

add_index "comment_hierarchies", ["ancestor_id", "descendant_id", "generations"], name: "comment_anc_desc_udx", unique: true
add_index "comment_hierarchies", ["descendant_id"], name: "comment_desc_idx"

create_table "comments", force: true do |t|
  t.string   "body"
  t.string   "author"
  t.string   "post_id"
  t.boolean  "deleted"
  t.boolean  "locked"
  t.datetime "created_at"
  t.datetime "updated_at"
end

编辑: 我通过更改页面上的表单以从

发表新评论来修复它
<%= form_for([@post, @post.comments.build], :html => {:class => 'ui form'}) do |f| %>
          <div class="field">
            <%= f.text_area :body, placeholder: "Comment", style: "max-height: 100px;"%>
          </div>
          <p>
            <%= f.submit "Add Comment", class: "blue ui button" %>
          </p>
      <% end %>

<%= form_for([@post, Comment.new], :html => {:class => 'ui form'}) do |f| %>
          <div class="field">
            <%= f.text_area :body, placeholder: "Comment", style: "max-height: 100px;"%>
          </div>
          <p>
            <%= f.submit "Add Comment", class: "blue ui button" %>
          </p>
      <% end %>

您能否在此之前的某处调用 @post.comments.new 来呈现评论表单?这可能是在 association_cache.

中添加新的非持久记录

为避免这种情况,您应该能够将评论实例化为 Comment.new(post_id: @post.id)。这不应该将评论添加到 association_cache。如果是这样,您真的不需要新 Comment 上的 post_id。无论如何你可能把它放在一个隐藏的字段中。

似乎您的数据库中针对此post的评论。

c.body 可能 return nil,它本身并不能定义你的数据库中没有评论记录。也许你刚才没有验证或者在控制台上手动跳过了它。

c.inspect 会更详细地说明对象中的数据。

你如何确认你的数据库是空的? @post.comments.count 是否等于 0?