【问题标题】:MissingMethodException showing up on save action保存操作时出现 MissingMethodException
【发布时间】:2012-03-29 01:34:46
【问题描述】:

我正在使用 Grails in Action 中的一个示例,特别是第一次实现服务并将工作从控制器转移到服务。

我有一个包含用户和字符串内容的 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")
    }

}

控制器代码是

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。然后将所述 params 对象传递给 Service,在 Service 中创建新的 Post 并将其绑定到用户。

但是,我在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() 错误,但在控制器上却没有?

【问题讨论】:

    标签: exception grails


    【解决方案1】:

    user 是您传递给服务方法的字符串。 thisUser 是您获得的实际 User 对象,您可以调用 save() on。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多