1

Let's say we have a resourceful Student model. I have a query regarding updating a student resource via PUT api.

If we send a put request to PUT /students/1 along with request body containing the few attributes that we want to update.

Let's the Student having many attributes like name,age,rollno,country,dob and we just want to update the country, so in the put request body we will pass something like {country: 'germany'} , some other request might pass only the dob.

How should we handle it in server side to only update the attributes passed in the body ?

Deepak Kumar Padhy
  • 4,128
  • 6
  • 43
  • 79
  • Technically, this would want to be `PATCH` instead of `PUT`, discussed some [here](https://stackoverflow.com/questions/28459418/rest-api-put-vs-patch-with-real-life-examples). If you did `resources :students`, your `update` route already supports `PUT` or `PATCH` – Simple Lime Jul 31 '17 at 14:37

1 Answers1

1

The update method on your ActiveRecord objects takes an attributes hash. You can pass only one attribute, or all attributes of a model, and ActiveRecord will figure out what has changed and only update those columns and leave the rest alone.

student = Student.create(name: 'name', age: 'age', rollno: 'rollno', country: 'country', dob: 'dob')

params = { country: 'germany' } # stand-in for your actual params hash in the controller

student.update(params)

Only country will be updated, everything else will remain the same. On the next request when you update dob it works the same way.

params = { dob: '1/1/2000` }

student.update(params)
m. simon borg
  • 2,515
  • 12
  • 20
  • But i do not know which keys are coming in api request body. – Deepak Kumar Padhy Jul 31 '17 at 15:25
  • Right, I'm just showing you how that doesn't matter. Assuming that you have parameters coming in some hash-like object, in this case the hash is stored in a variable called `params`. If you pass the hash to the `update` method you will get a partial update like you want – m. simon borg Jul 31 '17 at 15:31
  • Your question is sort of broad, so if you're also asking how to handle the incoming params all the way through the routing and controller level then you should clarify that and read through the guides first http://guides.rubyonrails.org/action_controller_overview.html. – m. simon borg Jul 31 '17 at 15:37
  • @DeepakKumarPadhy since you said you `have a resourceful Student model`, I assumed you aren't asking about routing and controllers and params hashes, and are just asking about the API to perform the actual database update : ) let me know if the answer can be improved – m. simon borg Jul 31 '17 at 15:47