Skip to content

Instantly share code, notes, and snippets.

@bastianccm
Created February 26, 2020 13:20
Show Gist options
  • Save bastianccm/875988bf5682a0c8a5a1bde30e075909 to your computer and use it in GitHub Desktop.
Save bastianccm/875988bf5682a0c8a5a1bde30e075909 to your computer and use it in GitHub Desktop.
//...
func (c *controller) vote(ctx context.Context, request *web.Request) web.Result {
questionID, err := strconv.Atoi(request.Params["question_id"])
if err != nil {
return c.responder.ServerError(err)
}
var question Question
if c.db.Preload("Choices").First(&question, questionID).RecordNotFound() {
return c.responder.NotFound(gorm.ErrRecordNotFound)
}
var choice Choice
choiceIDstr, err := request.Form1("choice")
if err != nil {
return c.noSelectedChoice(question)
}
choiceID, err := strconv.Atoi(choiceIDstr)
if err != nil {
return c.noSelectedChoice(question)
}
for _, c := range question.Choices {
if c.ID == uint(choiceID) {
choice = c
break
}
}
if choice.ID == 0 {
return c.noSelectedChoice(question)
}
choice.Votes++
c.db.Save(&choice)
return c.responder.RouteRedirect("results", map[string]string{"question_id": strconv.Itoa(questionID)})
}
func (c *controller) noSelectedChoice(question Question) web.Result {
var viewData struct {
Question Question
ErrorMessage string
}
viewData.Question = question
viewData.ErrorMessage = "You didn't select a choice."
return c.responder.Render("detail", viewData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment