diff --git a/callbacks/associations.go b/callbacks/associations.go index 283a2666..bbfbbc3d 100644 --- a/callbacks/associations.go +++ b/callbacks/associations.go @@ -73,6 +73,8 @@ func SaveAfterAssociations(db *gorm.DB) { if ref.OwnPrimaryKey { fv, _ := ref.PrimaryKey.ValueOf(db.Statement.ReflectValue) ref.ForeignKey.Set(f, fv) + } else if ref.PrimaryValue != "" { + ref.ForeignKey.Set(f, ref.PrimaryValue) } } } diff --git a/tests/create.go b/tests/create.go index b8e9245b..10b6b699 100644 --- a/tests/create.go +++ b/tests/create.go @@ -1,6 +1,7 @@ package tests import ( + "fmt" "testing" "github.com/jinzhu/gorm" @@ -106,4 +107,25 @@ func TestCreateAssociations(t *testing.T, db *gorm.DB) { } } }) + + t.Run("Create-HasOneAssociation-Polymorphic", func(t *testing.T) { + var pet = Pet{ + Name: "create", + Toy: Toy{Name: "Create-HasOneAssociation-Polymorphic"}, + } + + if err := db.Create(&pet).Error; err != nil { + t.Fatalf("errors happened when create: %v", err) + } + + if pet.Toy.OwnerID != fmt.Sprint(pet.ID) || pet.Toy.OwnerType != "pets" { + t.Errorf("Failed to create polymorphic has one association - toy owner id %v, owner type %v", pet.Toy.OwnerID, pet.Toy.OwnerType) + } else { + var toy Toy + db.First(&toy, "owner_id = ? and owner_type = ?", pet.Toy.OwnerID, pet.Toy.OwnerType) + if toy.Name != "Create-HasOneAssociation-Polymorphic" { + t.Errorf("Failed to query saved polymorphic has one association") + } + } + }) } diff --git a/tests/model.go b/tests/model.go index 4d686a57..1ae7c160 100644 --- a/tests/model.go +++ b/tests/model.go @@ -44,6 +44,7 @@ type Pet struct { type Toy struct { gorm.Model + Name string OwnerID string OwnerType string }