如何从列表中删除项目而不是在Grails(归档概念)中的数据库中删除?

时间:2011-11-01 04:06:44

标签: grails groovy

我刚接触grails,我试图在grails中实现存档。那就是当我尝试从列表中删除项目时,它必须在列表中删除,但不能在数据库中删除。在数据库中,标记将出现在列表中的已删除项目上。  请指导我解决这个问题。

1 个答案:

答案 0 :(得分:3)

您将向相关域添加active布尔字段,以便可以将相关对象标记为活动或非活动。您还必须在相应的域控制器中自定义删除操作,以便不删除该对象,因为您只需要将active布尔值更改为false而不是删除。然后,在相应域控制器的列表操作中,您必须在列出它们之前过滤掉所有非活动对象。

<强>更新

请参阅下面的代码,了解我的建议。

//The User domain class
class User {
    String username
    boolean active = true    
}

//The delete action of the User controller
def delete = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            //Here instead of deleting the user, we just mark the user as inactive.
            userInstance?.active = false
            //You may choose to change this message to something that indicates the user is
            //now inactive instead of deleted since the user is not really being deleted.
            flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
                flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
                redirect(action: "list")
        }
}   

//The list action of the User controller
def list = {
        def users = User.findAll("from User as users where users.active=false")
        //Instead of writing "userInstance: User.list()" I filtered out all inactive users
        //and created the "users" object then wrote "userInstance: users". Build in other
        //parameters as you see fit.
        [userInstanceList: users]    
}