创建域类的新实例不保存

时间:2013-02-28 20:56:07

标签: grails gorm

我想要创建一个新的实例,而不是保存一个编辑的域类,我已经制定了这些更改。

def update =
{
        def VariantInstance = Variant.get(params.id)
        VariantInstance.properties = params
        def NewVariantInstance = new Variant()
        //Now Assign Variant Instance new Values
        NewVariantInstance.Name = VariantInstance.Name
        NewVariantInstance.LocationID = VariantInstance.LocationID
        NewVariantInstance.aliases = VariantInstance.aliases
        NewVariantInstance.closeToBoundary = VariantInstance.closeToBoundary


        if (VariantInstance) {
        if (!VariantInstance.hasErrors() && !NewVariantInstance.hasErrors()) {
            println("no errors")
            try {
            NewVariantInstance.save()
            }
            catch (Exception ex)
            {
                println(ex.toString())
            }


            flash.message = "${message(code: 'default.updated.message', args: [message(code: 'Variant.uniqueIdentifyingName', default: 'Variant'), VariantInstance.id])}"
            redirect(action: "list")
        }

}

然而,当我经历这个A)没有保存新版本和B)NewVariantInstance没有id。思考?

1 个答案:

答案 0 :(得分:2)

您的VariantInstanceNewVariantInstance从未经过验证,因此hasErrors()将始终返回false。你需要从

切换
!VariantInstance.hasErrors() && !NewVariantInstance.hasErrors()

VariantInstance.validate() && NewVariantInstance.validate()

NewVariantInstance可能存在验证错误,因此save()未成功。