grails - 命令对象和 hasman

标签 grails command-objects

我在提交表单时尝试使用 commandObject 来验证我的数据。我可以验证 commandObject 中的 hasMany 关系吗?我的场景是这样的。

两个简单的,其中有很多关系:

class Book{
    String nameBook
}

class Author{
    String nameAuthor
    static hasMany = [books:Book]    
}

简单的commandObject与hasMany,我想在提交表单时进行验证。

@grails.validation.Validateable
class MyValidateCommand{

    String nameAuthor
    static hasMany = [books:Book]


    static constraints = {
        nameAuthor nullable:false
        books nullable:false
    }

}

Ps:我知道这个commandObject是错误的,它无法编译。但我可以做这样的事情吗???

最佳答案

GORM 中的

hasMany 用于 Domain 对象中的关联。对于命令对象,为每个域使用不同的命令对象(例如:AuthorCommandBookCommand)将是一种清晰的方法,命令对象如下所示:

import org.apache.commons.collections.list.LazyList
import org.apache.commons.collections.functors.InstantiateFactory

//Dont need this annotation if command object 
//is in the same location as the controller
//By default its validateable
@grails.validation.Validateable
class AuthorCommand{
    String nameAuthor
    //static hasMany = [books:Book]

    //Lazily initialized list for BookCommand
    //which will be efficient based on the form submission.
    List<BookCommand> books = 
            LazyList.decorate(new ArrayList(), 
                              new InstantiateFactory(BookCommand.class))

    static constraints = {
        nameAuthor nullable:false
        books nullable:false

        //Let BookCommand do its validation, 
        //although you can have a custom validator to do some 
        //validation here.
    }
}

关于grails - 命令对象和 hasman,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382346/

相关文章:

css - 包括外部 css grails 渲染插件问题

Grails Controller ,命令对象爆炸

grails - 为什么这个 Spring Batch Bean 没有在 Grails 中自动连接?

hibernate - GORM中子查询的平均值

json - Json null数据表现异常

grails - Grails表单重定向/渲染的最佳实践

grails - 在 GRAILS 中创建与其他类型对象不同类型的对象时需要建议如何使用服务

grails - 时髦的, chalice : high level questions on extraneous properties and command objects/data binding

validation - Grails命令对象临时字段验证

facebook - grails spring-security-oauth-facebook:0.2