【发布时间】:2015-04-19 18:11:29
【问题描述】:
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 %>
【问题讨论】:
-
closure_tree是什么? -
尝试
<%= c.inspect %>或<%= c.attributes %>来查看返回的评论是否是表单的内置评论(没有id值),或者它是否实际保存在数据库中。
标签: ruby-on-rails sqlite activerecord