Sunday, 15 January 2012

scala - Case classes, persistence and Play forms -



scala - Case classes, persistence and Play forms -

over course of study of creating basic application using play , anorm i've encountered problem when dealing entities not yet saved database. form doesn't have field id can't create mapping using case class apply method. ended creating 2 classes - 1 persisted entities , 1 not yet persisted , code looks this

case class ephemeraluser(email: string) case class persistentuser(id: long, email: string) val userform = form(mapping("email" -> text))(ephemeraluser.apply)(ephemeraluser.unapply) def create(user: ephemeraluser): persistentuser = { /* save anorm */ }

is there more elegant way deal using single case class user(id: option[long], email: string) ? or better, way remove code repetition cause kinda fact persisted , ephemeral users different types.

i don't think it's necessary require 2 types. making id option[long] should enough. test if model has been persisted require check user.id.isdefined.

your form utilize ignored still take advantage of apply , unapply:

case class user(id: option[long], email: string) val userform = form { mapping( "id" -> ignored[option[long]](none), "email" -> email )(user.apply)(user.unapply) }

scala playframework playframework-2.0

No comments:

Post a Comment