kofhearts
kofhearts

Reputation: 3774

correct way to implement delete feature in grails?

I have a delete method which looks something like

Controller Method

def deletemap(Long id){


    try {

        mapService.deleteMap(id)

    }
    catch (ValidationException e) {


        flash.message = "Sorry an error occured when deleting map!!"

        redirect(action: "maps", id: event.id)

        return


    }


    flash.message = "Map was deleted!!"

    redirect(action: "maps", id: event.id)

    return


}

The controller method calls service method which looks as follows:

Service Method

def deleteMap(id){


    def map = Map.get(id)



    if(map == null){

            throw new org.springframework.security.access.AccessDeniedException("Id doesn't exist!!!")
            return
    }



    map.delete(flush: true)

}

My goal is to implement this feature as best to completion as possible. I am currently writing some tests and am wondering whether i should handle the case in test when map.delete(flush: true) fails. Can there be a case when this gorm call fails? I appreciate any help! Thanks!

Upvotes: 0

Views: 2195

Answers (1)

rvargas
rvargas

Reputation: 635

A clean way to do it:

Controller

def deletemap(Long id){

    Map mapInstance = Map.get(id)

    if (!mapInstance) {
        flash.message = "Map not found"
    }
    else {
        mapService.deleteMap(mapInstance)
        flash.message = "Map was deleted!!"
    }

    redirect(action: "maps")
}

Service

def deleteMap(Map mapInstance){
    map.delete(flush: true)
}

If Map has a relation with other domains, it will fail; in this case, you need to validate if a relation exists and delete that one or tell your user that a relation prevents deletion. But that depends in your domain design.

Upvotes: 1

Related Questions