保存操作的奇怪行为

时间:2016-01-06 00:18:32

标签: grails

我对域名保存有一种奇怪的行为,这是域名:

class Ads {
String adTitle
String adDetails
String duration
Date dateCreated

static belongsTo = [user:Users]

static constraints = {
    category (nullable:false)
    adTitle (nullable:false, maxSize:100 )
    adDetails(nullable:false, maxSize:500 )
    duration (inList:["7 days", "14 days", "30 days"],nullable:true)
}

static mapping ={ duration (sqlType:"datetime") }
}

这是控制器中的保存操作

    @Transactional
def save(Ads adsInstance) {
    if (adsInstance == null) {
        notFound()
        return
    }

    if (adsInstance.hasErrors()) {
        respond adsInstance.errors, view:'create'
        return
    }
    adsInstance.user=Users.get(springSecurityService.currentUserId)

    def adCreationDate = new Date()

    switch (adsInstance.duration) {//here i'm just modifying the duration 
        case "7 days":
            adsInstance.duration=adCreationDate+7

            break
        case "14 days":
            adsInstance.duration=adCreationDate+14

            break
        case "30 days":
            adsInstance.duration=adCreationDate+30

            break
        default:
            adsInstance.duration=adCreationDate+7

    }
    adsInstance.save flush:true
    if (adsInstance.isAttached()) //here the return is always not saved
    {
        println "Saved"
    }
    else
    {
        println " not Saved"
    }
    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.created.message', args: [
                message(code: 'ads.label', default: 'Ads'),
                adsInstance.id
            ])
            //  redirect adsInstance
            redirect action:'show' ,id:adsInstance.id
        }
        '*' { respond adsInstance, [status: CREATED] }
    }
}

adsInstance.isAttached()我总是得到未保存虽然 adsInstance.save flush:true 在它之前被调用,我是遗失了什么?

1 个答案:

答案 0 :(得分:1)

你遗漏了两件事:

  • 修改持续时间字段后,您不会再次验证该对象。
  • 如果您使用save方法添加了failOnError: true,那么您自己就已经确定了问题。

您在duration字段上添加了一个约束,它只能包含值["7 days", "14 days", "30 days"]。但是在切换块内部,您要为其分配日期类型值,这些值不会通过验证。其次,根据验证,duration字段的sql类型不应为datetime。您应该创建自定义验证器或使用瞬态字段。