Updating Single Records

In order to update a single record most times you will use the Where function.

package main

import (
    "bitbucket.org/pop-book/models"
    "fmt"
    "github.com/gobuffalo/pop"
    "log"
)

func main() {
    tx, err := pop.Connect("development")
    if err != nil {
        log.Panic(err)
    }

    query := tx.Where("title = 'Ms.'")
    users := []models.User{}
    err = query.All(&users)
    if err != nil {
        fmt.Print("ERROR!\n")
        fmt.Printf("%v\n", err)
    } else {
        for i := 0; i < len(users); i++ {
            user := users[i]
            user.Title = "Mrs."
            tx.ValidateAndSave(&user)
            fmt.Print("Success!\n")
            fmt.Printf("%v\n", user)
        }
    }
}

Here, you basically collect a slice of users and you update that set using the ValidateAndSave function that we've seen before. Compiling and running yields

$ ./main
Success!
{"id":"bf3ba75b-8dfe-4619-b832-31c4a087a589","created_at":"2017-12-19T14:06:20.473953-05:00","updated_at":"2017-12-28T21:57:45.771782-05:00","title":"Mrs.","first_name":"Jessica","last_name":"Jones","bio":"Private security, super hero.","location":"NYC, NY"}

results matching ""

    No results matching ""