我有一个标准的grails(1.3.7)脚手架 Controller ,保存闭包如下:
def save = {
// ... instantiate and save "instance" ...
redirect(action: "show", id: instance.id)
}
...和一个“之后”过滤器,例如:
def filters =
{
save(controller:'*', action:'save')
{
after =
{
// How do I get the newly created entity's ID here?
}
}
有没有一种方法可以在任何 Controller 中的过滤器中访问新实体的ID,而不必向每个 Controller 添加任何额外的/特殊的代码?
最佳答案
按照splix的建议将其保存在请求中,或者考虑改用拦截器。在“afterInterceptor”中,您可以直接访问模型。见Controller Interceptors
更新了
根据您的评论,您可以使用元编程技术并拦截域类上的每个“afterInsert”调用。例如,如果将其添加到Bootstrap中:
grailsApplication.domainClasses.each { org.codehaus.groovy.grails.commons.GrailsDomainClass gc ->
gc.metaClass.afterInsert = {
println "$id"
}
}
您应该能够访问所有新创建的域对象并执行常见操作。
关于grails - 从Grails “after”过滤器访问重定向ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9322896/