Sunday, January 6, 2013

Grails read-only domain class


Grails does not provide simple mapping to mark domain object read-only, means so that dynamic find methods (find, get, list..) work OK but save/delete is forbidden. This is particularly useful for legacy databases.
We can however provide desired behavior with low effort ourselved.
I could think out at least 2 ways of doing so:
1. listen on beforeXXX methods in domain class e.g.:

class Demo {

    static constraints = {
    }
    String name

    transient beforeUpdate = {
        throw new RuntimeException('update not allowed')
    }
}

2. send error status from controler REST method that is not allowed, e.g.:


    def delete(Long id) {
        response.sendError(405)
    }

If you just want to disable an attribute of a domain class from being editable in scaffolded view you can use constraint:

class Demo {

    static constraints = {
         name(editable: false)
    }
    String name
}

1 comment:

  1. You can also get simillar behavior if set cache to readonly
    static mapping = {
    cache usage: 'read-only'
    }

    ReplyDelete