I'm devolping a rating system with RichUI plugin for Grails. First I had the following code:
class 开发者_StackOverflowRatingController {
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)
}
}
which worked fine, but the problem with this code is that, if the user updates the rating for one artist it would always create a new Rating instance instead of just update the rating value. So I came up with the following code:
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)
}
}
But with this code, when the rating value is assigned to the new rating (params.rating) in the "else" block, it is assigned to some random number around 50's (like 53). I can not see where is the problem. A little help would be appreciated. Thanks very much.
I just found out where the problem was. I had to convert the input value of the rating to type double. So, the following code is working as it was supposed to:
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)
}
}
精彩评论