def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
答案 0 :(得分:1)
它与路由有关。如果你只为一个控制器路由,例如/ comments /:id那么你只需要使用params [:id]来获取params,但是如果你有多个控制器和多个id涉及并且可以访问那么它就像是/ posts /:id / comments /:comment_id以避免混淆:您访问的ID。
def destroy
@post = Post.find(params[:id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
上面的代码会出现问题,因为rails不知道哪个:id要抓取,所以我们区分使用:post_id和:comment_id
答案 1 :(得分:0)
我猜我们在这里看到了一个CommentsController的一部分。我假设每个评论属于一个帖子。因此id
此处将引用评论(模型),post_id
引用帖子。您应该仔细查看评论和发布模型。