2
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 
4

2 回答 2

1

它与路由有关。如果你只为一个控制器路由,例如,/comments/:id 那么你只需要使用 params[:id] 来获取参数,但是如果你有多个控制器并且多个 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 来区分

于 2012-10-11T15:39:12.780 回答
0

我猜我们在这里看到了 CommentsController 的一部分。我假设每个评论都属于一个帖子。所以id这里将引用一个评论(模型)和post_id一个帖子的引用。您应该仔细查看 Comment 和 Post 模型。

于 2012-10-11T15:35:37.943 回答