以下模板基于http://guides.rubyonrails.org/getting_started.html
的rails指南我正在创建内联的“real_comments”以避免由@ article.comments.build格式创建的额外空注释,但是这会导致错误,因为当我尝试删除它时,注释ID丢失了。
No route matches [DELETE] "/articles/2/comments"
是否可以删除构建创建的额外注释,同时维护用于对注释执行操作的索引?我自己想出了一个real_comments解决方案,所以我毫不怀疑我正在做一些导致问题的非导轨问题
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<%#How to copy an array in ruby %>
<% real_comments = @article.comments.map do |e|
e.dup
end %>
<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
<p>
<%= f.label :commenter %>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<h2>Comments:</h2>
<% real_comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<%= link_to 'Destroy Comment', [comment.article, comment], method: :delete, data: {confirm: 'Are you sure?'} %>
<% end %>
<%= link_to 'Edit', edit_article_path(@article) %>
<%= link_to 'Back', articles_path %>
答案 0 :(得分:1)
您可以使用persisted?
方法来过滤掉尚未保存的记录
<h2>Comments:</h2>
<% @article.comments.select(&:persisted?).each do |comment| %>
...