Skip to content

Instantly share code, notes, and snippets.

@junhuif
Created December 2, 2015 03:30
Show Gist options
  • Save junhuif/bb1bc2379d0d857cd52a to your computer and use it in GitHub Desktop.
Save junhuif/bb1bc2379d0d857cd52a to your computer and use it in GitHub Desktop.
Gorm doesn't insert false value into database for boolean field
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
var DB *gorm.DB
type Post struct {
Title string
CommentsEnabled bool `sql:"default:true"`
}
func panicIfErr(err error) {
if err != nil {
panic(err)
}
}
func init() {
db, err := gorm.Open("postgres", "user=hui dbname=gorm_test sslmode=disable")
panicIfErr(err)
DB = &db
DB.AutoMigrate(&Post{})
}
func main() {
post := Post{Title: "A test post", CommentsEnabled: false}
err := DB.Debug().Create(&post).Error
panicIfErr(err)
// DB log: INSERT INTO "posts" ("title") VALUES ('A test post') RETURNING "posts".*
// Output: true
fmt.Println(post.CommentsEnabled)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment