我有一个用户域类,如下所示:
package xyz
class User {
String login
String password
String firstName
String lastName
String address
String email
static hasMany = [
websites: AddWebsite
]
static constraints = {
login blank:false, size:5..15,matches:/[\S]+/, unique:true
password blank:false, size:5..15,matches:/[\S]+/
firstName blank:false
lastName blank:false
email email: true
}
}
和另一个AddWebsite域类如下:
package xyz
import xyz.User;
class AddWebsite {
String website
User user
static belongsTo = [user: User]
static constraints = { website url:true }
}
我在后端使用MongoDB。我需要每个登录的用户都可以添加网站,但用户不能多次添加相同的网站,但不同的用户可以添加相同的网站。每当我尝试添加一个网站时,它都会显示我"用户不能为空错误"。
我的AddWebsite控制器类如下:
package xyz
class AddWebsiteController {
def index() {
}
def addWebsites() {
if(request.method == 'POST') {
def u = new AddWebsite()
u.properties[
'website'
] = params
if(u.website =="" ) {
u.errors.rejectValue("website", "addwebsite.website.empty")
return [addWebsite:u]
}
else if(u.save()) {
render view:'addWebsites', model:[message: "Successfully saved: \""+u.website+"\" Add more websites..."]
//redirect(controller: "AddWebsite", action: "websiteAdded")
}
else {
return [addWebsite:u]
}
}
}
def websiteAdded() {
}
def failed(){
}
}
另外,我不知道如何测试这一对多关联。请帮忙。
答案 0 :(得分:0)
想出来。我在控制器中进行了此更改,以便用户不再为null:
def addWebsites() {
if(request.method == 'POST') {
def w = new AddWebsite()
w.properties[
'website'
] = params
w.user = session["user"] //modified
if(w.website =="" ) {
w.errors.rejectValue("website", "addwebsite.website.empty")
return [addWebsite:w]
}
else if(w.save()) {
render view:'addWebsites', model:[message: "Successfully saved: \""+w.website+"\" Add more websites..."]
}
else {
return [addWebsite:w]
}
}
}