可选参数路线 - 玩2.1斯卡拉(Routes with optional parameter -

2019-07-20 06:12发布

因此,在播放2.0我有这样的:

GET     /tasks/add              controllers.Tasks.addTask(parentId: Option[Long] = None)
GET     /tasks/:parentId/add    controllers.Tasks.addTask(parentId: Option[Long])

有了这样的控制器的方法:

def addTask(parentId: Option[Long]) = Action { 
    Ok(views.html.addTask(taskForm, parentId))  
}

而且这是工作。 当我迁移到2.1,似乎抱怨这些线路搭配: No URL path binder found for type Option[Long]. Try to implement an implicit PathBindable for this type. No URL path binder found for type Option[Long]. Try to implement an implicit PathBindable for this type. 基本上,我想做到的是有航线tasks/add和路由tasks/123/add链接到一个接受同样的方法Optional[Long] 。 任何想法如何做到这一点? 谢谢。

好了,我得到了一种它不是一个错误,这是对灯塔的特征回应:“我们删除选项[龙]路径bindables,因为它没有任何意义有一个可选路径参数的支持,您可以实现自己的支持它,如果你请的路径绑定“。 到目前为止,我有2个解决方案,通过为-1 parentId的,我真的不喜欢。 或有2种不同的方法,这可能更有意义在这种情况下。 实施PathBindable似乎并没有太多可行的,现在,所以我可能会与具有2种方法坚持下去。

Answer 1:

玩2.0的支持Option的路径参数,播放2.1不再支持这一点,他们取消了期权的PathBindable。

一个可能的解决办法是:

package extensions
import play.api.mvc._
object Binders {
  implicit def OptionBindable[T : PathBindable] = new PathBindable[Option[T]] {
    def bind(key: String, value: String): Either[String, Option[T]] =
      implicitly[PathBindable[T]].
        bind(key, value).
        fold(
          left => Left(left),
          right => Right(Some(right))
        )

    def unbind(key: String, value: Option[T]): String = value map (_.toString) getOrElse ""
  }
}

这增加Build.scala使用routesImport += "extensions.Binders._" 运行play clean ~run ,它应该工作。 在飞行中重新加载粘合剂只是有时工作。



Answer 2:

我认为你必须添加一个问号:

controllers.Tasks.addTask(parentId: Option[Long] ?= None)



Answer 3:

从这个路线与-可选参数的建议是这样:

GET   /                     controllers.Application.show(page = "home")
GET   /:page                controllers.Application.show(page)


Answer 4:

简单的解决问题的方法,而不必通过默认值,是添加包装在一个选项的参数一个简单的代理方法。

路线:

GET     /tasks/add              controllers.Tasks.addTask()
GET     /tasks/:parentId/add    controllers.Tasks.addTaskProxy(parentId: Long)

控制器:

def addTask(parentId: Option[Long] = None) = Action { 
    Ok(views.html.addTask(taskForm, parentId))  
}

def addTaskProxy(parentId: Long) = addTask(Some(parentId))


Answer 5:

我有同样的事情多,如果你指定通作为GET/foo:idcontrollers.Application.foo(id : Option[Long] ?= None) ,你得到一个错误It is not allowed to specify a fixed or default value for parameter: 'id' extracted from the path的另一边,你可以做如下GET/foo controllers.Application.foo(id : Option[Long] ?= None) ,也将努力期待您的请求看起来像作为.../foo?id=1



文章来源: Routes with optional parameter - Play 2.1 Scala