Grails update instead of delete

感情迁移 提交于 2019-12-03 13:40:49

问题


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 = {}
}


来源:https://stackoverflow.com/questions/8768534/grails-update-instead-of-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!