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 %>
,但表没有记录。如果我将该代码更改为
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
我一无所获。
也许它使用closure_tree
对我有所帮助。
如果有帮助,这里是表的架构:
<%= 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 %>
到
{{1}}
答案 0 :(得分:3)
你可以在此之前的某个地方调用@post.comments.new
来呈现评论表吗?这可能是在association_cache
中添加新的非持久记录。
为避免这种情况,您应该能够将评论实例化为Comment.new(post_id: @post.id)
。这不应该将注释添加到association_cache。如果是,您实际上不需要新post_id
上的Comment
。无论如何,你可能在隐藏的领域中拥有它。
答案 1 :(得分:0)
似乎 在您的数据库中为此帖子保留了评论。
c.body
可能返回nil,仅此一项并未定义数据库中没有注释记录。也许你刚才没有验证或在控制台上手动跳过它。
c.inspect
会为您提供有关对象中数据的详细信息。
您如何确认您的数据库是空的? @post.comments.count
是否等于0?