Rails shows that an instance of the Comment model exists, even though the database is empty. My code to show the Comment is
<% @post.comments.each do |c| %>
<%= c %>
<% end %>
And from that, I get #<Comment:0x007fe971c02800> also if i do c.attributes I get
{"id"=>nil, "body"=>nil, "author"=>nil, "post_id"=>37, "deleted"=>nil, "locked"=>nil, "created_at"=>nil, "updated_at"=>nil}, but the table has no records. If I change that code to
<% @post.comments.each do |c| %>
<%= c.body %>
<% end %>
I get nothing.
Maybe it has something to me using closure_tree.
If it helps, here is the schema for the 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
EDIT: I fixed it by changing the form on the page to make a new comment from
<%= 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 %>
to
<%= 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 %>
Could you be calling @post.comments.new somewhere before this to render the comment form? This could be adding the new, non-persisted record in the association_cache.
To avoid this, you should be able to instantiate the comment as Comment.new(post_id: @post.id). This shouldn't add the comment to the association_cache. If it does, you really don't need the post_id on the new Comment. You probably have it in a hidden field anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With