Stephen Lead
Stephen Lead

Reputation: 1976

How to update an existing Rails model object via a JSON post operation?

I'm writing data into a Rails model, using Python to send the JSON (to demonstrate I created a simple scaffold Book with a title and price):

import json, urllib2    
httpHeaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}

bookData = {"title": "blah", "price":5}  
req = urllib2.Request("http://localhost:3000/books.json", json.dumps({"book": bookData}), httpHeaders)
response = json.loads(urllib2.urlopen(req).read())

This inserts the book and gives it ID = 1:

# http://localhost:3000/books/1.json
{"id": 1,"title": "blah","price": 5}

How can I now edit this record via JSON, for example to change the price?

Upvotes: 0

Views: 296

Answers (1)

Stephen Lead
Stephen Lead

Reputation: 1976

In the process of writing the question I stumbled on the answer, so rather than deleting it I decided to post the question and answer, since I can't see it asked elsewhere on SO.

rake routes shows that the update method uses PATCH (rather than GET or PUT) so this answer to How do I make a PATCH request in Python helped me to figure this out in a Python/Rails context:

bookData = {"price":60}
req = urllib2.Request("http://localhost:3000/books/1.json", json.dumps({"book": bookData}), httpHeaders)
req.get_method = lambda: 'PATCH'
response = json.loads(urllib2.urlopen(req).read())

Upvotes: 1

Related Questions