2

我想用不同的 Input 进行拖曳操作,并使一个能够调用另一个:

def showQuestion(questionId :Long)=Action{
     Redirect(routes.Application.showQuestion(Question.find.byId(questionId)))
 }
 def showQuestion(question :Question)=Action{
    Ok(views.html.show(question))
 }

我尝试了上述但没有运气。编译器抱怨:

found   : models.Question
[error]  required: Long
[error]      Redirect(routes.Application.showQuestion(Question.find.byId(questionId)))

指第一个。

4

2 回答 2

1

我认为你错过了一些东西。

在您的routes文件中,您无法将 URL 映射到第二个操作:

GET /question/:id    controllers.Question.showQuestion(id: Long)
GET /question/:question    controllers.Question.showQuestion(question: Question) // <== how to map the "question" in the Url ???

那么为什么不这样做(在这种情况下,使用两种方法并不真正相关):

def showQuestion(questionId: Long)=Action{
     showQuestion(Question.find.byId(questionId))
}

private def showQuestion(question: Question)=Action{
    Ok(views.html.show(question))
}
于 2013-01-30T14:24:55.453 回答
0

这不是一个直接的答案,但是有一些值得思考的地方:

  1. 路由器的主要任务是从请求到函数参数的参数转换类型验证,因此最好使用一些常见的类型,例如String,IntBool来识别 DB 中的对象,而不是尝试通过路由器传递整个对象。实际上,您的第一条路线可以正确地做到这一点。
  2. 我找不到任何充分的理由使用两个单独的操作来查找对象和渲染模板(在其他操作中找到对象)。更重要的是,你正试图通过 来做到这一点Redirect,所以它创建了两个请求,这是多余的!您应该只删除第二条路线并使用一项操作:

    GET /question/:id    controllers.Question.showQuestion(id: Long)
    
    def showQuestion(questionId: Long)=Action{
       Ok(views.html.show(Question.find.byId(questionId)))
    }
    
  3. 如果您真的非常想将其拆分为两个单独的功能,请使用@nico_ekito的示例,我认为您也可以在这种情况下删除第二条路线。

  4. 如果将来您想要重载函数...最好不要这样做:) 重载很好,当您在许多地方都有可使用的静态方法并且它可能因参数数量等而有所不同时。很可能它会是使用不同的动作名称更舒服(即使路线相似):

    GET  /question/:id     controllers.Question.showById(id: Long)
    GET  /question/:name   controllers.Question.showByName(name: String)
    
    // so finally in the view you can use it just as:
    <a href='@routes.Question.showById(item.id)' ...
    <a href='@routes.Question.showByName(item.name)' ...
    
于 2013-01-30T22:12:34.057 回答