Grails:Duplicates&唯一约束验证

时间:2010-05-23 23:27:56

标签: validation grails gorm

好的,这是我在我的应用程序中删除的版本

艺术家域名:

class Artist {

    String name
    Date lastMined
    def artistService

    static transients = ['artistService']
    static hasMany = [events: Event]

    static constraints = {
        name(unique: true)
        lastMined(nullable: true)
    }

    def mine() {
        artistService.mine(this)
    }
}

活动领域:

class Event {

    String name
    String details
    String country
    String town
    String place
    String url
    String date

    static belongsTo = [Artist]
    static hasMany = [artists: Artist]

    static constraints = {
        name(unique: true)
        url(unique: true)
    }
}

ArtistService:

class ArtistService {

    def results = [
        [
            name:"name",
            details:"details",
            country:"country",
            town:"town",
            place:"place",
            url:"url",
            date:"date"
        ]
    ]

    def mine(Artist artist) {
        results << results[0] // now we have a duplicate
        results.each {
            def event = new Event(it)
            if (event.validate()) {
                if (artist.events.find{ it.name == event.name }) {
                    log.info "grrr! valid duplicate name: ${event.name}"
                }
                artist.addToEvents(event)
            }
        }

        artist.lastMined = new Date()
        if (artist.events) {
            artist.save(flush: true)
        }
    }
}

理论上,event.validate()应该返回false并且不会将事件添加到artist,但它不会..这会导致artist.save()上的DB异常

虽然我注意到如果重复事件持续存在,首先一切都按预期工作。是bug还是功能? :P

2 个答案:

答案 0 :(得分:2)

哪个版本的Grails?我刚刚在Grails 1.3.1控制台中测试了这段代码:

new Book(title: "Misery", author: "Stephen King").save()
new Book(title: "The Shining", author: "Stephen King").save()
new Book(title: "Colossus", author: "Niall Ferguson").save(flush: true)

def b = new Book(title: "Colossus", author: "Stephen King")
assert !b.validate()
println b.errors

断言传递,最后一行生成输出,如:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'Book' on field 'title': rejected value [Colossus]; codes [Book.title.unique.error.Book.title,...

也许这是一个现在修复的错误?

答案 1 :(得分:2)

您应该artist.addToEvents(event)替换artist.addToEvents(event).save(),它会起作用。 直到你没有调用save()方法,验证将不会考虑新创建的事件