这些创建方法之间的区别?Ruby on Rails



我有一个博客,我正在通过以下代码创建评论。我注意到两者以(似乎(完全相同的方式工作。

在视图中调用此创建方法的以下两种方法是否有任何优点和缺点?是否有更多方式可以调用此类活动?

PostComment通过has_manybelongs_to关系联系在一起。

  1. <%= simple_form_for([@post, Comment.new]) do |f| %>

  2. <%= 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之间没有真正的区别,因为buildnew的别名。

您还可以将buildnew放入new控制器操作中:

def new
@post = Post.new
@comment = @post.comment.build
end

然后只需使用表单中的实例变量:

<%= simple_form_for([@post, @comment]) do |f| %>

最新更新