2

以下代码来自Play 2 ScalaTodoList 教程

楷模:

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()
    }
  }

现在,我正在尝试添加名为Description的第三个属性:

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方法中。如何包含description到 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)
      }
    )
4

1 回答 1

2

目前,newTask 是一个Form[String]:封装单个数据的表单,一个字符串。

您需要使用更复杂的表单来处理标签和描述。您可以case class为这两个值定义 a ,或者简单地使用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

** 现在,您可以在控制器中检索这些值

// 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()
   }
 }

仅供参考,valuesformerrors任意变量名。你可以选择你想要的。

ps:您也需要调整您的 Form(...)

于 2012-12-20T07:47:47.910 回答