开发者

Update via HTTP POST

开发者 https://www.devze.com 2023-03-16 14:05 出处:网络
There are lots of threads on here debating when to use HTTP PUT vs. POST. However, its clear that it should be possible to update records via either method.

There are lots of threads on here debating when to use HTTP PUT vs. POST. However, its clear that it should be possible to update records via either method.

Without going into irrelevant detail, I'd like to create or update a record via POST.

If I understand this correctly, I should be able to achieve this based on whether I include the id of an existing record or not in the HTTP Body. If the POST includes an id, then it's an update, otherwise it's a create request (and the newly created record with id will be returned in response).

As such,

PUT: http://www.database.com/record/99 (with record attributes in HTTP body)

is equivalent to,

POST: http://www.database.com/records (with record id=99 and attributes in HTTP body)

My code to POST works fine for creating new records (i.e. when I don't includ开发者_运维问答e an id). However when I include the id in the HTTP Body it is ignored, and the server just performs a create, not an update.

As such, I'd like to know, is my understanding of how a POST HTTP Body is interpreted correct?


Your interpretation of how the POST body is interpreted is incorrect.

The ID needs to be in the URL for it to be recognised as an update. The URL specifies the resource being updated, not the body.

Sticking to the Rails convention of POST for create and PUT for update is much easier than trying to fight with it. The conventions are there for a reason, so you don't have to worry about stuff like this.


Its depends on your routes > I you are using the default scaffold, the only action for PUT is UPDATE (in where you have to pass the ID)

With scaffold the routes method and action are:

  • GET for show, index, edit, new
  • POST for create
  • PUT for update
  • DELETE for destroy
0

精彩评论

暂无评论...
验证码 换一张
取 消