Grails Scaffolding - define possible values for this property of a domain class

一个人想着一个人 提交于 2019-12-05 07:49:41

From the documentation http://grails.org/doc/latest/guide/scaffolding.html, you should be able to use an inList constraint:

class Person {
    String firstName
    String lastName
    String gender
    Date dateOfBirth

    def constraints = {
        gender( inList: ["M", "F", "U"])
    }
}

This should scaffold to a select list for the gender field, depending on the version of Grails you're using. 2.0+ definitely does this.

Here is an alternative solution

class Person {
    String firstName
    String lastName
    enum Gender {
        M(1),
        F(2),
        U(3)
        private Gender(int val) { this.id = val }
        final int id
    }
    Gender gender = Gender.U
    Date dateOfBirth

    def constraints = {
        gender()
    }
}

This will store gender in the database as an integer (1,2,3) and default the gender to U. The benefit here is you can rename what F, M, and U mean without handling a data migration.

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