1

I'm trying to create a restful method to update data in the database, I'm using Scala on Play! framework. I have a model called Application, and I want to be able to update an application in the database. So the put request only requires the id of the application you want to update, then the optional properties you want to update.

So in my routes I have this:

PUT     /v1/auth/application        controllers.Auth.update_application(id: Long)

The method I currently have is this:

def update_application(id: Long) = Action { implicit request =>
        var app = Application.find(id)
        for((key, value) <- request.queryString) {
             app."$key" = value(0)
             //app.name = value(0)
        }
        val update = Application.update(id, app)
        Ok(generate(
            Map(
                "status" -> "success",
                "data"   -> update
            )
        )).as("application/json")
   }

In the method above I am looping through the request and the app object as a map instance, then updating the app model to be updated using the model. I know there is an easier way is to create the request string as map and just iterate through the object, but I am doing it this way for learning purposes. I'm new to Play! and Scala, barely a week new.

Is there a way to set a property using a variable dynamically that way? In the above method at the end of the loop that is how I would update a object's property in Groovy. So I'm looking for the equivalent in Scala. If Scala can't do this, what is the best way about going about accomplishing this task? Reflection? I don't want to over-complicate things

1 Answer 1

1

Play! provides play.api.data.Forms which allows creating a Form that uses the apply() and unapply() methods of a case class. Then you can call form.fill(app) to create a form with the initial state, bindFromRequest(request) to update the form with the request parameters, and get() to obtain a new instance with updated fields.

Define the form only once:

val appForm = Form(
  mapping(
    "field1" -> text,
    "field2" -> number
  )(Application.apply)(Application.unapply)
)

Then in your controller:

val app = appForm.fill(Application.find(id)).bindFromRequest(request).get
val update = Application.update(id, app)

Check out Constructing complex objects from the documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.