Grails update instead of delete

2020-05-28 11:35发布

问题:

Is there an easy way in Grails to not allow deleting for any Domain Class? And rather have a delete flag in each domain which gets updated whenever something is deleted.

Also, in effect all the list/show methods should not show objects where delete flag is true.

I know I can do that by manually editing all my CRUD methods in all the controllers but that seems a little bit too much work when working with Grails where everything can be done by changing some flag somewhere!!

My usual list method looks like following, almost all the list methods in my project lets user access things which only belongs to users' company.

def list = {
    params.max = Math.min(params.max ? params.int('max') : 10, 100)
    def documentsList = Documents.createCriteria().list(params){
        eq("company.id",session.companyId)  
        maxResults(params.max)
        order("dateCreated","desc")
        //firstResult(params.offset)
    }
    [documentsInstanceList: documentsList , documentsInstanceTotal: documentsList.getTotalCount() ]
}

回答1:

You'll have to ovveride the delete and list methods of all your domain classes. Add code like this to your Bootstrap

class BootStrap {

  def grailsApplication

  def init = { servletContext ->

  for (dc in grailsApplication.domainClasses) {

     dc.clazz.exists(-1);  //to register meta class

     def gormSave = dc.clazz.metaClass.getMetaMethod('save');         
     dc.clazz.metaClass.delete = {  ->
        delegate.deleted = true
        gormSave.invoke delegate
     }

     dc.clazz.metaClass.delete = { Map args  ->
        delegate.deleted = true
        gormSave.invoke(delegate, args)
     }

     dc.clazz.metaClass.static.list = {  ->
        def crit = delegate.createCriteria();
        def list = crit.list{
          eq('deleted', false)
        }
        return list;
     }



  }
}

   def destroy = {}
}