[英]Rails AR record includes 'new' unsaved record
I have a view for an 'article' show action. 我有一个“文章”表演行动的看法。
Articles have comments. 文章有评论。
The view displays: a) article b) comments c) new comment form 该视图显示:a)文章b)评论c)新评论表单
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. 当遍历@comments时,我发现该列表还包含来自控制器动作的新记录。 I can avoid displaying this row using:
我可以避免使用以下方式显示此行:
<% if !comment.new_record? %>
...
<% end %>
Am I doing this wrong or is this the expected behaviour? 我做错了这还是预期的行为?
Yes it is expected because of how you are creating the new Comment
. 是的,因为您是如何创建新的
Comment
所以可以预期。 You are basically adding a new empty Comment
to your @article.comments
before you render them in the view. 在将它们在视图中呈现之前,您基本上是在
@article.comments
添加新的空Comment
。 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. 您的解决方案很有意义,但您也可以通过不在控制器
show
动作中将@article
分配给新的@comment
来避免该问题。
So instead of @comment = @comments.new
you would do @comment = Comment.new
. 因此,您可以使用
@comment = Comment.new
而不是@comment = @comments.new
。 Then, inside your form for the @comment
you would add a field for the article_id
. 然后,在
@comment
的表单内,您将为article_id
添加一个字段。
<%= f.hidden_field :article_id, :value => @article.id %>
This will allow you to maintain the relationship in your Comment.create
action. 这将允许您在
Comment.create
操作中维护关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.