Rails AR record includes 'new' unsaved record

删除回忆录丶 提交于 2019-12-12 09:18:42

问题


I have a view for an 'article' show action.

Articles have comments.

The view displays: a) article b) comments c) new comment form

My controller is action is:

def show
  @article = Article.find(params[:id])
  @comments = @article.comments
  @comment = @comments.new
end

The view displays the comments using a partial.

<%= render @comments %>

When looping through @comments I am finding the list also contains the new record from the controller action. I can avoid displaying this row using:

<% if !comment.new_record? %>
  ...
<% end %>

Am I doing this wrong or is this the expected behaviour?


回答1:


Yes it is expected because of how you are creating the new Comment. You are basically adding a new empty Comment to your @article.comments before you render them in the view. Your solution makes sense but alternatively you could avoid the issue by not assigning the @article to the new @comment inside your controller show action.

So instead of @comment = @comments.new you would do @comment = Comment.new. Then, inside your form for the @comment you would add a field for the article_id.

<%= f.hidden_field :article_id, :value => @article.id %>

This will allow you to maintain the relationship in your Comment.create action.



来源:https://stackoverflow.com/questions/31018338/rails-ar-record-includes-new-unsaved-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!