Scala Play Framework 2.6-定义使用自定义对象的路由
在packageScala Play Framework 2.6-定义使用自定义对象的路由,scala,routes,playframework-2.6,Scala,Routes,Playframework 2.6,在packagemodels中,我有以下案例类别: case class Property (id: Option[Long], address: String, postCode: Int, latitude: Double, longitude: Double, surface: Option[Int],
models
中,我有以下案例类别:
case class Property (id: Option[Long],
address: String,
postCode: Int,
latitude: Double,
longitude: Double,
surface: Option[Int],
bedRoomCount: Option[Int])
object Property {
implicit val propertyFormat = Json.format[Property]
}
我正在尝试配置通过属性对象的路由:
POST /update-property controllers.PropertyController.update(property: models.Property)
我的控制器定义了一个动作:
def update(property: Property) = Action.async { implicit request =>
...bla bla bla...
}
我得到了以下编译错误:
[error] conf/routes:8:1: No QueryString binder found for type models.Property. Try to implement an implicit QueryStringBindable for this type.
[error] POST /update-property controllers.PropertyController.update(property: models.Property)
[error] conf/routes:8:1: not enough arguments for method implicitly: (implicit e: play.api.mvc.QueryStringBindable[models.Property])play.api.mvc.QueryStringBindable[models.Property].
[error] Unspecified value parameter e.
我错过了什么?是否可以使用
属性
数据填充表单?正如编译错误所说,您需要实现一个隐式QueryStringBindable
。大概是这样的:
object Binders {
//return the error message on the left should the parsing fail
private def propertyFromString(s: String): Either[String, Property] = ???
private def propertyToString(property: Property): String = ???
implicit def queryStringBindable(implicit stringBinder: QueryStringBindable[String]): QueryStringBindable[Property] = new QueryStringBindable[Property] {
override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Property]] = {
for {
eitherPropString <- stringBinder.bind("property", params)
} yield {
eitherPropString match {
case Right(propString) => propertyFromString(propString)
case _ => Left("Unable to bind property")
}
}
}
override def unbind(key: String, property: Property): String = {
stringBinder.unbind("property", propertyToString(property))
}
}
}
这样您的
路由
文件就可以访问活页夹
对象。文件是。如果您想将属性
字段作为单独的查询参数传入,请参阅文档中的AgeRange
示例。包名不应该是models
而不是models.Property
?models是包,Property.scala是文件名
routesImport += "path.to.Binders._"