Creating New Records
Before we query for any records, it's useful to have some data to look at so we'll create some data. First, let's inspect our user model struct:
type User struct {
ID uuid.UUID `json:"id" db:"id"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
Title string `json:"title" db:"title"`
FirstName string `json:"first_name" db:"first_name"`
LastName string `json:"last_name" db:"last_name"`
Bio string `json:"bio" db:"bio"`
}
The first three fields - ID, CreatedAt, UpdatedAt - are autogenerated by pop because pop enforces the ActiveRecord pattern, as stated in the introduction. The last four are the fields that we declared when building the model, as stated in the quick start. Recalling all of this, let's create five users (in main.go).
package main
import (
"log"
"bitbucket.org/pop-book/models"
"github.com/gobuffalo/pop"
)
func main() {
tx, err := pop.Connect("development")
if err != nil {
log.Panic(err)
}
jessica := models.User{Title: "Ms.", FirstName: "Jessica", LastName: "Jones", Bio: "Private security, super hero."}
_, err = tx.ValidateAndSave(&jessica)
if err != nil {
log.Panic(err)
}
luke := models.User{Title: "Mr.", FirstName: "Luke", LastName: "Cage", Bio: "Hero for hire."}
_, err = tx.ValidateAndSave(&luke)
if err != nil {
log.Panic(err)
}
danny := models.User{Title: "Mr.", FirstName: "Danny", LastName: "Rand", Bio: "Martial artist."}
_, err = tx.ValidateAndSave(&danny)
if err != nil {
log.Panic(err)
}
matt := models.User{Title: "Mr.", FirstName: "Matthew", LastName: "Murdock", Bio: "Lawyer, sees with no eyes."}
_, err = tx.ValidateAndSave(&matt)
if err != nil {
log.Panic(err)
}
frank := models.User{Title: "Mr.", FirstName: "Frank", LastName: "Castle", Bio: "USMC, badass."}
_, err = tx.ValidateAndSave(&frank)
if err != nil {
log.Panic(err)
}
}
Go ahead and compile then run this. If you use your sqlite client and query you should see something like
sqlite> SELECT * FROM users;
bf3ba75b-8dfe-4619-b832-31c4a087a589|Ms.|Jessica|Jones|Private security, super hero.|2017-12-19 14:06:20.473953-05:00|2017-12-19 14:06:20.473956-05:00
61b2db41-a66b-4093-8580-be0b114ec04e|Mr.|Luke|Cage|Hero for hire.|2017-12-19 14:06:20.476127-05:00|2017-12-19 14:06:20.476128-05:00
d86df65e-2bf8-4bec-9b23-8d7b274a401a|Mr.|Danny|Rand|Martial artist.|2017-12-19 14:06:20.476837-05:00|2017-12-19 14:06:20.476838-05:00
bd73c1a3-0259-4e0a-a3b2-232cf94b52ff|Mr.|Matthew|Murdock|Lawyer, sees with no eyes.|2017-12-19 14:06:20.47763-05:00|2017-12-19 14:06:20.477631-05:00
240ec3c5-019d-4031-9c27-8a553e022297|Mr.|Frank|Castle|USMC, badass.|2017-12-19 14:06:20.478384-05:00|2017-12-19 14:06:20.478385-05:00
Now that we have some data, we can run some other operations.