더북(TheBook)

10.3.6 각 포스트 보여주기

포스트 목록 페이지에서 각 포스트에 show 링크를 보여주고, 링크를 클릭했을 때 상세 페이지로 이동하여 포스트 내용을 보여주는 기능을 구현해 보자.

 

Show 액션 메서드 작성

app/controller/post.go 파일에 Show 액션 메서드를 추가한다.

▼ app/controllers/post.go

func (c Post) Show(id int) revel.Result {
    post, err := getPost(c.Txn, id)
    if err != nil {
        panic(err)
    }
     
    return c.Render(post)
}
 
func getPost(txn *sql.Tx, id int) (models.Post, error) {
    post := models.Post{}
    err := txn.QueryRow("select id, title, body, created_at, updated_at from posts where id=?", id).
        Scan(&post.Id, &post.Title, &post.Body, &post.CreatedAt, &post.UpdatedAt)
     
    switch {
    case err == sql.ErrNoRows:
        return post, fmt.Errorf("No post with that ID - %d.", id)
    case err != nil:
        return post, err
    }
    return post, nil
}

Show 액션은 id 값으로 포스트 하나에 해당하는 데이터베이스의 레코드를 조회한다. id로 포스트를 조회하는 기능은 포스트를 수정할 때도 사용되므로 별도의 함수로 만들었다. 매개변수로 전달된 id로 포스트를 조회해서 post 변수에 저장하고 c.Render(post)로 렌더링해주면 뷰에서 post에 접근할 수 있다.

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