以下代码来自Play 2 ScalaTodoList tutorial :
型号:
case class Task(id: Long, label: String)
object Task {
val task = {
get[Long]("id")~
get[String]("label") map {
case id~label => Task(id, label)
}
}
def all(): List[Task] = DB.withConnection { implicit c =>
SQL("select * from task").as(task *)
}
def create(label: String) {
DB.withConnection { implicit c =>
SQL("insert into task (label) values ({label})").on(
'label -> label
).executeUpdate()
}
}
现在,我尝试添加第三个属性,名为描述:
case class Task(id: Long, label: String, description: String)
object Task {
val task = {
get[Long]("id")~
get[String]("label")~
get[String]("description") map {
case id~label~description => Task(id, label, description)
}
}
(我是 Scala 初学者,不确定我是否做对了)
但我陷入了 def create
方法。如何在 SQL 查询中包含 description
?
编辑:
我也不确定如何在此处包含描述
:
def newTask = Action { implicit request =>
taskForm.bindFromRequest.fold(
errors => BadRequest(views.html.index(Task.all(), errors)),
label => {
Task.create(label)
Redirect(routes.Application.tasks)
}
)
最佳答案
目前,newTask 是一个Form[String]
:封装单个数据(字符串)的表单。
您需要使用更复杂的表单来处理标签和描述。
您可以为这两个值定义一个case class
,或者简单地使用Tuple
case class TaskForm(label: String, description: Form)
在这两种情况下,您至少需要进行修改:
** 更改模板中的表单类型:
taskForm: Form[String] => taskForm: Form[(String, String)] // with a tuple
或
taskForm: Form[String] => taskForm: Form[TaskForm] // with the case class defined above
** 现在,您可以在 Controller 中检索这些值
// with tuple
taskForm.bindFromRequest.fold(
errors => BadRequest(views.html.index(Task.all(), errors)),
values => { Task.create(values._1, values._2) .... }
或
// with case class
taskForm.bindFromRequest.fold(
errors => BadRequest(views.html.index(Task.all(), errors)),
form => { Task.Create(form.label, form.description) }
当然,您必须向 Create 添加第二个参数(或传递 caseclass/tuple 对象)
def create(label: String, description: String) {
DB.withConnection { implicit c =>
SQL("insert into task (label, description) values ({label}, {description})").on(
'label -> label,
'description -> description
).executeUpdate()
}
}
仅供引用,values
、form
和 errors
是任意变量名称。您可以选择您想要的。
ps:您也需要调整您的 Form(...)
关于scala - 玩 2 Scala : Adding a description attribute to this model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13965406/