我正在尝试使用带有 Play 框架的 Scala 开发一个小型 Web 应用程序。它有一个名为 Product 的模型,其中包含一个Float类型的字段price。
通过 HTML 表单接受浮点值并将其保存在测试数据库中的最佳方法是什么?
我正在使用 sorm 作为测试数据库。
我正在尝试使用带有 Play 框架的 Scala 开发一个小型 Web 应用程序。它有一个名为 Product 的模型,其中包含一个Float类型的字段price。
通过 HTML 表单接受浮点值并将其保存在测试数据库中的最佳方法是什么?
我正在使用 sorm 作为测试数据库。
我看到您定义了您的模型,如下所示:
case class Product(price: Long)
此外,您的表格可能如下所示:
val productForm = Form(
mapping(
"price" -> longNumber(minLength = 2, maxLength = 10)
)(Product.apply)(Product.unapply)
)
你的问题有两个部分:
您有 html 表单供用户提交数据。现在您需要编写操作来验证数据以及它是否有效推送到 db 或显示错误消息。在这里,您可以执行以下操作:
def save = Action { implicit request =>
productForm.bindFromRequest.fold(
errors => BadRequest(views.html.product.create(errors)),
data => {
//insert data and redirect to listing view so that he can see the new data
productCollection.insert(data)
Redirect(routes.product.list())
.withNewSession
}
)
}
Play 支持 H2 内存数据库,如果您不想使用它,您可以通过注释以下行来添加自己的数据库配置:
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
并在下面添加详细信息:
db.default.user=user
db.default.password=qwerty
db.default.url="jdbc:postgresql://localhost:5432/"
db.default.driver=org.postgresql.Driver