2011-07-01 53 views
1

我使用RichUI插件爲Grails開發了一個評分系統。首先,我有以下代碼:RichUI的問題star rating

class RatingController { 

def springSecurityService 

static scaffold = true 

def rate = { 
    def rating = params.rating 
    def artist = Artist.get(params.id) 
    def currentUser = currentUser() 

    currentUser.addToRatings(new Rating(artist:artist, rating:rating)).save() 
    render(template: "/artist/rate", model: [artist: artist, rating: rating]) 

    } 

private currentUser(){ 
    return User.get(springSecurityService.principal.id) 
} 
} 

它工作得很好,但是這個代碼的問題是,如果用戶更新的等級爲一個藝術家它總是創建一個新的評級實例,而不是隻更新評級值。 於是我想出了下面的代碼:

class RatingController { 

def springSecurityService 

static scaffold = true 

def rate = { 
    def rating = params.rating 
    def artist = Artist.get(params.id) 
    def currentUser = currentUser() 

    if(! currentUser.ratings.artist.contains(artist)){ 
     currentUser.addToRatings(new Rating(artist:artist, rating:rating)).save() 
     render(template: "/artist/rate", model: [artist: artist, rating: rating]) 
    } 

    else{ 
     currentUser.ratings.find{it.artist==artist}.rating = rating 
     currentUser.save() 
     render(template: "/artist/rate", model: [artist: artist, rating: rating]) 
    } 
} 

private currentUser(){ 
    return User.get(springSecurityService.principal.id) 
} 
} 

但有了這個代碼,當評價值被分配到「其他」塊新的等級(params.rating),它被分配給一些隨機數量在50左右(如53)。我看不出問題在哪裏。 有一點幫助,將不勝感激。 非常感謝。

回答

2

我剛剛發現問題出在哪裏。我必須將評分的輸入值轉換爲double類型。所以,下面的代碼工作,因爲它本來是:

class RatingController { 

    def springSecurityService 

    static scaffold = true 

    def rate = { 
     def rating = params.rating.toDouble() 
     def artist = Artist.get(params.id) 
     def currentUser = currentUser() 

     if(! currentUser.ratings.artist.contains(artist)){ 
      currentUser.addToRatings(new Rating(artist:artist, rating:rating)).save() 
      render(template: "/artist/rate", model: [artist: artist, rating: rating]) 
     } 

     else{ 
      currentUser.ratings.find{it.artist==artist}.rating = rating 
      currentUser.save() 
      render(template: "/artist/rate", model: [artist: artist, rating: rating]) 
     } 
    } 

    private currentUser(){ 
     return User.get(springSecurityService.principal.id) 
    } 
    } 
+0

FWIW,一個「更巧妙」的方式來做到這將是'高清等級= params.rating作爲Double' - 沒有太大的不同,但不同的選項如果您有興趣瞭解其他語法。 :) –