exception - 保存操作时出现 MissingMethodException

我正在使用 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")
    }

}

Controller 代码是

def addPost = {
  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: []
如果我删除服务连接器并将 Controller 中的服务代码实现为
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/

相关文章:

grails - 无法从Grails连接到MySQL

grails - Grails Spring安全性插件镜像访问控制

grails - Grails UI性能插件页面压缩问题

hibernate - Grails命名查询NOT IN

grails - Grails 应用程序中的 CMS

grails - 什么是java.lang.NoClassDefFoundError:org/apa

grails - 使设计适应 Grails

grails - 动态Groovy上传到Grails应用程序

hibernate - Grails数据源 “Cannot add or update a chil

grails - 在Grails中,是否可以将数据库迁移插件配置为在其他插件之前运行?