더북(TheBook)

10.5.4 새로 분리한 템플릿에 댓글 삭제 기능 추가하기

뷰를 기능에 따라 별도의 템플릿으로 분리하는 작업을 완료했다. 지금부터 분리한 템플릿에 새 기능을 추가해 보자. _comment.html 파일에 댓글 삭제 기능을 추가해 본다.

먼저 app/controller/comment.go 파일에 Destroy 액션 메서드를 작성하자.

▼ app/controllers/comment.go

func (c Comment) Destroy(postId, id int) revel.Result {
    // 댓글 삭제
    if _, err := c.Txn.Exec("delete from comments where id=?", id); err != nil {
        panic(err)
    }
     
    // 뷰에 Flash 메시지 전달
    c.Flash.Success("댓글 삭제 완료")
     
    // 포스트 상세 보기 화면으로 이동
    return c.Redirect(routes.Post.Show(postId))
}

다음으로 라우트에 Destroy 액션을 정의해 보자. /posts/:postId/comments/:id를 통해 DELETE 방식으로 요청을 보내거나, /posts/:postId/comments/:id/delete URL을 통해 GET 방식으로 요청을 보냈을 때 Comment 컨트롤러의 Destroy 액션으로 전달되게 conf/routes 파일에 다음과 같이 추가한다.

▼ conf/routes

GET      /posts/:postId/comments/:id/delete   Comment.Destroy

DELETE   /posts/:postId/comments/:id          Comment.Destroy


신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.