Grails更新而不是删除 [英] Grails update instead of delete
问题描述
Grails中有没有简单的方法来禁止删除任何Domain Class?而且,每当某个东西被删除时,每个域中都会有一个删除标志。
实际上,所有list / show方法都不应该显示删除标志为真的。
我知道我可以通过手动编辑所有控制器中的所有CRUD方法来实现这一点,但在使用Grails时,看起来工作量有点过大,通过改变某个标志的位置来完成!!
我的通常列表方法看起来像下面,几乎我项目中的所有列表方法都允许用户访问只属于用户的东西,公司。
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)
}
[documentsInstanceL ist:documentsList,documentsInstanceTotal:documentsList.getTotalCount()]
}
您必须将所有域类的删除和列表方法列出。将这样的代码添加到您的Bootstrap中
class BootStrap {
def grailsApplication
def init = {servletContext - >
for(dc in grailsApplication.domainClasses){
dc.clazz.exists(-1); //注册元类
$ b $ def gormSave = dc.clazz.metaClass.getMetaMethod('save');
dc.clazz.metaClass.delete = { - >
delegate.deleted = true
gormSave.invoke委托
}
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 = {}
}
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() ]
}
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 = {}
}
这篇关于Grails更新而不是删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!