我正在使用 Grails in Action 中的一个示例,特别是第一次实现服务并将工作从 Controller 转移到服务。
我有一个包含用户和字符串内容的 Post 对象。
服务代码是
class PostService {
boolean transactional= true
Post createPost(String user, String content){
def thisUser = User.findByUserID(user)
if (user){
def post = new Post(content:content)
if (user.save()){
return post
} else
throw new PostException(message: "Invalid post", post:post)
}
throw new PostException(message:"Invalid User ID")
}
try{
def newPost = postService.createPost(params.id, params.content)
flash.message= "Added new Post: $newPost.content}"
} catch (PostException pe){
flash.message = pe.message
}
redirect(action:'timeline', id:params.id)
}
addPost
作为参数对象。然后将所述参数对象移交给服务,在该服务中将创建新的帖子并将其绑定(bind)到用户。user.save()
处收到错误消息.具体的错误信息是No signature of method: java.lang.String.save() is applicable for argument
types: () values: []
def user = User.findByUserID(params.id)
if (user) {
def post= new Post(params)
user.addToPosts(post)
if (user.save()){
flash.message= "Sucessfully created Post"
}
else {
user.discard()
flash.message = "Invalid or empty post"
}
} else {
flash.message = "Invalid User ID"
}
redirect(action: 'timeline', id:params.id)
}
user.save()
服务实现错误,但不是 Controller ?
最佳答案
user
是您传递给服务方法的字符串。 thisUser
是您获得的实际用户对象,您可以调用 save()
在。
https://stackoverflow.com/questions/9911953/