Rails的AR记录包括“新的”未保存记录 [英] Rails AR record includes 'new' unsaved record
问题描述
我有一个'文章'表演动作的图。
I have a view for an 'article' show action.
文章有意见。
该视图显示: 一)文章 B)评论 c)新的评论表单
The view displays: a) article b) comments c) new comment form
我的控制器操作:
def show
@article = Article.find(params[:id])
@comments = @article.comments
@comment = @comments.new
end
视图使用部分显示的评论。
The view displays the comments using a partial.
<%= render @comments %>
在通过@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?
推荐答案
由于你如何创建新的注释的是预计
。你基本上添加一个新的空注释
您 @ article.comments
您呈现他们的观点了。您的解决方案是有道理的,但或者,您可以通过不会分配 @article
新 @comment 回避的问题code>控制器里面
显示
操作。
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.
所以不是 @comment = @ comments.new
你会做 @comment = Comment.new
。然后,你的表格里面的 @comment
你会添加一个字段为的article_id
。
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 %>
这将让你保持你的 Comment.create
行动的关系。
This will allow you to maintain the relationship in your Comment.create
action.
这篇关于Rails的AR记录包括“新的”未保存记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!