0

问题是 - 我应该如何从这种输入中获取数据并将其正确传递给 DB(通过 SORM 框架)?

我尝试将数据传递给我的数据库中的两个表,我的工作结果是,虽然这些值被正确插入到第一个表(作者)中,但第二个表(书)保持不变。可能我的问题是我没有正确命名页面上的嵌套重复输入,但我找不到正确的方法来做到这一点(我对 Scala 相当陌生,所以我可能缺乏这方面的经验)。

Ok(Json.toJson(author)) 

在 Application.scala 的 addData 中向我展示

{"name":"what","books":[]}

所以我认为,问题在于从请求中绑定数据。

我在这里尝试遵循示例:如何在 Sorm 中为具有许多子对象的实体建模?在这里:https://www.playframework.com/documentation/2.1.1/ScalaForms,通过对 Play 框架中的模板“play-scala”进行操作,所以我有这样的代码:

型号有:

case class Author(name: String, books: Seq[Book]) {
}
object Author {
implicit val authorFormat = Json.format[Author]
}

case class Book(title: String ) {
}
object Book {
implicit val bookFormat = Json.format[Book]
}

case class AuthorBook(name: Author, title: Book) {
}

scala.index.html

<table>
    <tr>
        <td>
        On the left Author, on the right Book
        <td>
    </tr>
    <tr>
    <td>
        <ul id="authors"></ul>
    </td>
    <td>
        <ul id="books"></ul>
    </td>
    </tr>
</table>

<table>
    <form action="@routes.Application.addData()" method ="post">
        <tr>
            <td>Author: <input name="author" type="text">
        </td>       
            <td>Books: <input name="books.title[0]" type="text"><br><input name="books.title[1]" type="text">
        </td>
        </tr>
        <tr>
            <td> 
                <button>Submit</button>
            </td>
        </tr>
    </form>
</table>

和 Application.scala

class Application extends Controller {
def index = Action {
Ok(views.html.index("E-Library"))
}

  val authorForm: Form[Author] = Form {
    mapping(
      "author" -> text,
      "books" -> seq(
          mapping(
          "title" -> text)(Book.apply)(Book.unapply)
      )
   )(Author.apply)(Author.unapply)
   }

  def error = Action {
    Ok("error")
  }

  def addData = Action { implicit request =>
      authorForm.bindFromRequest.fold(
    formWithErrors => {
      BadRequest("Bad request!")
    },
    authorF => {
      val author = DB.save(authorF)
      Ok(Json.toJson(author))
      //Redirect(routes.Application.index())
    }
  )
  }

  def getAuthor = Action {
    val dataAuthor = DB.query[Author].fetch
    Ok(Json.toJson(dataAuthor))
  }

  def getBook = Action {
    val dataBook = DB.query[Book].fetch
    Ok(Json.toJson(dataBook))
 }

  def getData = Action {
    Redirect(routes.Application.index())
  }
}
4

1 回答 1

0

找到了!如此处所述:Play中的嵌套形式!斯卡拉 2.2

我需要将表单中的输入名称从 重命名 book.title[0]book[0].title

于 2015-09-11T18:46:23.487 回答