3
votes

I was trying to make a rest API for user registration and on that api there is a field named "gender", so I'm receiving that field as Struct but on user table there is no field for "gender". Is it possible to skip that "gender" field from struct while inserting with gorm?

This is my DataModel

package DataModels

type User struct {
    Id          uint `json:"id"`
    Otp         int `json:"otp"`
    UserId      string `json:"user_id"`
    UserType    string `json:"user_type"`
    FullName    string `json:"full_name"`
    MobileNo    string `json:"mobile"`
    Email       string `json:"email"`
    Gender      string `json:"gender"` // I want to skip this filed while inserting to users table
    Password    string `json:"password"`
}

func (b *User) TableName() string {
    return "users"
}

This my Controller Function

func CreateUser(c *gin.Context) {
    var user Models.User
    _ = c.BindJSON(&user)
    err := Models.CreateUser(&user) // want to skip that gender filed while inserting
    if err != nil {
        fmt.Println(err.Error())
        c.AbortWithStatus(http.StatusNotFound)
    } else {
        c.JSON(http.StatusOK, user)
    }
}

This is my model function for inserting

func CreateUser(user *User) (err error) {
    if err = Config.DB.Create(user).Error; err != nil {
        return err
    }
    return nil
}
2

2 Answers

4
votes

GORM allows you to ignore the field with tag, use gorm:"-" to ignore the field

type User struct {
    ...
    Gender   string `json:"gender" gorm:"-"` // ignore this field when write and read
}

Offical doc details about Field-Level Permission

2
votes

Eklavyas Answer is omitting gender always, not just on Create.

If I am correct you want to Skip the Gender field within the Registration. You can use Omit for that.

db.Omit("Gender").Create(&user)