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}
, 但该表没有记录。如果我将该代码更改为
<% @post.comments.each do |c| %>
<%= c.body %>
<% end %>
我一无所获。
也许它对我有用 closure_tree
.
如果有帮助,这里是表的架构:
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
。无论如何,您可能将它放在隐藏字段中。
关于ruby-on-rails - Rails 显示不存在的数据库记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28588761/