grails更新收藏夹onclick
我正在寻找一种方法来设置myFavorite表,在该表中单击列表项即可将其保存到myFavorite 给你grails更新收藏夹onclick,grails,Grails,我正在寻找一种方法来设置myFavorite表,在该表中单击列表项即可将其保存到myFavorite 给你 class user { static hasMany [favorite : Favorite] } class Favorite { //(no fields) just the two static's below static belongsTo [user :user] static hasMany [music : Music] } st
class user {
static hasMany [favorite : Favorite]
}
class Favorite {
//(no fields) just the two static's below
static belongsTo [user :user]
static hasMany [music : Music]
}
static constraints = {
id bindable: true
//id generator:'assigned'
user unique: true
music nullable: true
}
其目的是为每个人保留一个favorite.id,并在相同的id下添加音乐
这是我的控制器
def save() {
def authenticatedUser = User.findByUsername(springSecurityService.principal.username)
def principal = springSecurityService.principal
int userid = principal.id // id of the person logged in
def favorits = new Favorite(params) // form data
def check = Favorite.findByUsers(authenticatedUser) // check if myFavorite exist for user
def ids = check.id // id of the myFavorite
def tracks = check.tracks.id + favorits.tracks.id
def test2 = new Favorite(id:ids, 'users': userid, 'tracks': tracks)
if (check == null){// if user don't have Favorite create one
authenticatedUser.addToFavorite(favorits)
authenticatedUser.save flush: true
}
//render([test2] as JSON)
//test2.save flush: true
update(test2)
}
test2.save flush:true可以工作,但它会创建新的Favorite.ID实例来更新我传递的ID
Updatetest2还创建一个新id,而不是更新我传递的id。不要这样做:
def test2 = new Favorite(id:ids, 'users': userid, 'tracks': tracks)
您正在创建一个全新的收藏夹实例。如果要更新现有收藏夹,需要从数据库中检索现有实例,然后对其进行更改。试着这样做:
def test2 = Favourite.get(ids) //get the existing favourite by id
test2.users = ... //update some properties
test2.save()
如果每个用户只需要一个收藏夹,为什么不使用hasOne而不是hasMany?而是def authenticatedUser=user.findByUsernamespringSecurityService.principal.username write:def user=springSecurityService.currentUsers以及如何编写它不是grails风格