I'm trying to persist data with Scala/Slick in play framework. I'm sending a request via json and I'm trying to validate said request by matching it to a model like this:
request.body.asJson.map(_.validate[Foo] match {...}
The question is: How do I set a default column value (to false)?
This is my evolution file:
CREATE TABLE Foo(
...
deleted BOOLEAN NOT NULL DEFAULT FALSE,
...
)
This is my model (.scala):
case class Foo(
...
deleted: Boolean,
...)
This is my dao (.scala):
class Foo(tag: Tag) extends TableFoo(tag, "Foo"){
...
def deleted = column[Boolean]("deleted", O.Default(false))
...
def * = (..., deleted, ...) <> ((Foo.apply _).tupled, Foo.unapply)
}
The problem occurs while validating the request to the model. When defining deleted
as Option[Boolean]
, it writes None/Null
for the column deleted
. When defining it as Boolean
, the validation fails.
Presumably, because the request is missing the attribute deleted
.
Why defining a default value, when the validation fails after all or in the case of Option[Boolean]
just writes None/Null
? Is there an easy way to set a reliable default value in Scala/Slick or Evolutions?
deleted
. That's not what I wanted, since my back-end should function regardless of what's coming.case class Foo( ... deleted: Boolean=false, ...)
Not sure which version of play you're using but I think since 2.6 the json lib has a new functionally to allow for defaultsJson.WithDefaultValues
, I use an implicit format for thisimplicit val ModelFormat: OFormat[Model] = Json.using[Json.WithDefaultValues].format[Model]