0

I am using the play-salat plugin with an app I am making with Play! 2.0 scala.

I get the Duplicate Key error, and the compiler points here to the error:

object Post extends ModelCompanion[Post, ObjectId]

I have read that this can be fixed in PHP here doing an unset, please tell me how to do this with Play.

I am able to post in my database the once, when I try again I get the error.

def save = Action { implicit request =>
postForm.bindFromRequest.fold(
  formWithErrors => BadRequest(html.newpost(formWithErrors)),
  post => {
    Post.insert(post)
    Home
  }
)
}

val postForm = Form(
mapping(
  "_id" -> ignored(new ObjectId()),
  "title" -> nonEmptyText,
  "content" -> nonEmptyText,
  "posted" -> date("yyyy-MM-dd"),
  "modified" -> optional(date("yyyy-MM-dd")),
  "tags" -> nonEmptyText,
  "categories" -> nonEmptyText,
  "userId" -> nonEmptyText
)(Post.apply)(Post.unapply)
) 
4

1 回答 1

0

我自己解决了这个问题。我对 Scala 和 Play Framework 很陌生。

我像这样更改了我的 Application.scala 文件:

def newpost = Action {
Ok(views.html.newpost(postForm))
}

def save = Action { implicit request =>
postForm.bindFromRequest.fold(
  formWithErrors => BadRequest(html.newpost(formWithErrors)),
  post => {
    Post.create(post.title, post.content, post.posted, post.modified, post.categories, post.tags, post.author)
    Home.flashing("success" -> "Post %s has been created".format(post.title))
  }
)
}

val postForm = Form(
mapping(
  "_id" -> ignored(new ObjectId()),
  "title" -> nonEmptyText,
  "content" -> nonEmptyText,
  "posted" -> date("yyyy-MM-dd"),
  "modified" -> optional(date("yyyy-MM-dd")),
  "categories" -> nonEmptyText,
  "tags" -> nonEmptyText,
  "author" -> nonEmptyText
)(Post.apply)(Post.unapply)
)

我还更改了我的 Post.scala 文件:

 object PostDAO extends SalatDAO[Post, ObjectId](
collection = MongoConnection()("blog")("posts"))

 object Post {

  def create(title: String, content: String, posted: Date = new Date(), modified: Option[Date] = None, categories: String, tags: String, author: String) {
    PostDAO.insert(Post(
        title = title,
        content = content,
        posted = posted,
        modified = modified,
        categories = categories,
        tags = tags,
        author = author
        ))
  }

  def delete(id: String) {
    PostDAO.remove(MongoDBObject("_id" -> new ObjectId(id)))
}
}
于 2012-08-13T01:11:25.057 回答