goweb-frameworksbuffalo

Cannot ValidateAndCreate model in gobuffalo


I am having trouble using pop.Connection#ValidateAndCreate in gobuffalo.

    purchaseOrder.Items = models.OrderItems{}

    ... fill purchaseOrder.Items ...

    for _, item := range purchaseOrder.Items {

        verrs, err := tx.ValidateAndCreate(item)
        if err != nil {
            return errors.WithStack(err)
        }

        if verrs != nil {
            // show error
        }
    }

tx is type *github.com/gobuffalo/pop.Connection

I get the error: reflect: call of reflect.Value.Elem on struct Value on the line verrs, err := tx.ValidateAndCreate(item)


Solution

  • ValidateAndCreate requires the item as a pointer, since it needs to update the ID property in case it's auto-generated. Pop manages the CreatedAt and UpdatedAt attributes too, so it have to change those too.

    As proposed by mkopriva, you can change the ValidateAndCreate call to:

    verrs, err := tx.ValidateAndCreate(&item)
    if err != nil {
        return errors.WithStack(err)
    }