2010-05-23 71 views
0

確定被剝離下來的我有什麼版本在我的應用程序的Grails:重複和獨特的約束驗證這裏

藝術家域:

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.save()

雖然我注意到如果重複事件是首先堅持一切按預期工作。它是錯誤還是功能? :P

+1

我不確定爲什麼重複邏輯失敗,但是在代碼中存在嚴重錯誤。服務是單身人士,但您已在此服務中共享狀態 - 「結果」列表。 當你是你的應用程序的唯一用戶(在開發模式下)時它會工作正常,但當你有多個併發訪問這個方法時會失敗。 – 2010-05-24 03:09:33

+0

在我的實際應用程序結果是在一個方法範圍內,但感謝提出,可能在未來幫助 – rukoche 2010-05-24 12:16:07

回答

2

,就應該替換由artist.addToEvents(event).save()artist.addToEvents(event),它會工作。 直到你沒有調用save()方法,驗證將不會考慮新創建的事件

+0

檢查它在測試應用程序 - 像魅力,我的實際應用程序 - 仍然會引起重複輸入異常。只保存(flush:true)消除了這個問題:| – rukoche 2010-05-24 13:56:02

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,... 

也許有人認爲現在修正了一個錯誤?