2

別の入力で2つのアクションを作成し、一方が他方を呼び出せるようにします。

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

あなたには何かが欠けていると思います。

ファイルでは、routesUrl を 2 番目のアクションにマップすることはできません。

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

では、なぜそのようなことをしないのでしょうか (この場合、2 つの方法を使用することは実際には関係ありません)。

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. ルーターの主なタスクは、要求から関数の引数へのパラメーターの変換型検証です。したがって、オブジェクト全体をルーターに渡そうとするのではなく、、などの一般的な型を使用してDB内のオブジェクトを識別することをStringお勧めします。実際、最初のルートはそれを適切に行います。IntBool
  2. オブジェクトの検索とテンプレートのレンダリング(他のアクションで見つかったオブジェクトを使用)に2つの別々のアクションを使用する正当な理由を見つけることができません。さらに、それを実行しようとしているので、 2つRedirectのリクエストが作成され、冗長になります。2番目のルートを削除して、次の1つのアクションを使用する必要があります。

    GET /question/:id    controllers.Question.showQuestion(id: Long)
    
    def showQuestion(questionId: Long)=Action{
       Ok(views.html.show(Question.find.byId(questionId)))
    }
    
  3. 本当に、本当に2つの別々の関数に分割したい場合は、@ nico_ekitoのサンプルを使用してください。そのような場合は、2番目のルートも削除できると思います。

  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 に答える