diff --git a/callback_query.go b/callback_query.go index f46d6ad4..8e6348f6 100644 --- a/callback_query.go +++ b/callback_query.go @@ -77,6 +77,15 @@ func Query(scope *Scope) { } if !anyRecordFound { + if isSlice && dest.IsNil() { + var emptySliceType reflect.Type + if isPtr { + emptySliceType = reflect.SliceOf(reflect.PtrTo(destType)) + } else { + emptySliceType = reflect.SliceOf(destType) + } + dest.Set(reflect.MakeSlice(emptySliceType, 0, 0)) + } scope.Err(RecordNotFound) } } diff --git a/query_test.go b/query_test.go index d4a68aa1..052d698c 100644 --- a/query_test.go +++ b/query_test.go @@ -78,6 +78,20 @@ func TestFindAsSliceOfPointers(t *testing.T) { } } +func TestFindWontReturnNilSlices(t *testing.T) { + randomNum := rand.Intn(1000000000) + + var users []User + DB.Where("name = ?", randomNum).Find(&users) + + var userPointers []*User + DB.Where("name = ?", randomNum).Find(&userPointers) + + if reflect.ValueOf(users).IsNil() || reflect.ValueOf(userPointers).IsNil() { + t.Errorf("Should have returned empty slices") + } +} + func TestSearchWithPlainSQL(t *testing.T) { user1 := User{Name: "PlainSqlUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "PlainSqlUser2", Age: 10, Birthday: now.MustParse("2010-1-1")}