Rails Put vs Post

后端 未结 4 1438
自闭症患者
自闭症患者 2021-01-04 06:12

I have been reading up on the difference between put and post requests and I have some related questions as it pertains to rails: I would like to change one specific field i

4条回答
  •  -上瘾入骨i
    2021-01-04 06:43

    • I think we should use PATCH when updating some attributes of record
    • PUT really means something among context of "replacing" the resource or all his attributes but could also means creating an resource (I'm basing this on what I remember from reading this book: REST API Design Rulebook ), For example when you are moving(copy) AWS S3 resource you are triggering PUT not POST. So yeah PUT is confusing.
    • POST should be used when submitting new resource

    There is lot of confusion around PATCH as well, I personally agree how JSON API standard is proposing to do it http://jsonapi.org/format/#crud-updating:

    PATCH /articles/1 HTTP/1.1
    Content-Type: application/vnd.api+json
    Accept: application/vnd.api+json
    
    {
      "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
          "title": "To TDD or Not"
        }
      }
    }
    

    I love Rails I but truth is it's not entirely following some core Web conventions. Rails is trying to be productive and too strict conventions are holding down the productivity. So don't go overboard when seeking answer for this. Truth is that Rails is treating PUT and PATCH the same way, and apparently both are wrong. So I recommend:

    • POST on create
    • PATCH on update
    • GET on index, new, show
    • don't use PUT at all
    • if you find yourself that your controller is doing some weird action, try to restructure your controllers (introduce new controller maybe http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/)

    But if your entire project is using PUT everywhere, you don't need to go through and change everything. Just stick to one or the other (PUT or the PATCH).

    UPDATE

    I've wrote 2 articles on this topic where I go in depth of this topic.

    • http://www.eq8.eu/blogs/36-patch-vs-put-and-the-patch-json-syntax-war
    • http://www.eq8.eu/blogs/37-post-create-and-put-updatepost

提交回复
热议问题