5

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?

4
  • any luck with this?
    – ezzarghili
    Commented Sep 30, 2017 at 20:24
  • @ezzarghili no, not so far. I just pass a default value from the front-end to the back-end for deleted. That's not what I wanted, since my back-end should function regardless of what's coming.
    – Nocebo
    Commented Oct 1, 2017 at 13:52
  • 1
    actually I got something working, define the default in the case class 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 defaults Json.WithDefaultValues, I use an implicit format for this implicit val ModelFormat: OFormat[Model] = Json.using[Json.WithDefaultValues].format[Model]
    – ezzarghili
    Commented Oct 1, 2017 at 14:18
  • @ezzarghili yeah I tried that once, but it didn't work for me. Maybe I just need to update my current version and the format. Thanks!
    – Nocebo
    Commented Oct 1, 2017 at 14:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.