我有一个博客,我正在通过以下代码创建评论。我注意到两者以(似乎(完全相同的方式工作。
在视图中调用此创建方法的以下两种方法是否有任何优点和缺点?是否有更多方式可以调用此类活动?
Post
和Comment
通过has_many
和belongs_to
关系联系在一起。
-
<%= simple_form_for([@post, Comment.new]) do |f| %>
-
<%= simple_form_for([@post, @post.comments.build]) do |f| %>
这是我comments_controller:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
if @comment.save
flash[:success] = "Comment created!"
redirect_to post_path(@post)
else
flash[:danger] = "Error"
redirect_to post_path(@post)
end
end
好吧,.new
和.build
之间没有真正的区别,因为build
是new
的别名。
您还可以将build
或new
放入new
控制器操作中:
def new
@post = Post.new
@comment = @post.comment.build
end
然后只需使用表单中的实例变量:
<%= simple_form_for([@post, @comment]) do |f| %>