Best practice for saving an entire collection?

后端 未结 4 1252
生来不讨喜
生来不讨喜 2020-12-08 06:55

Say that I have a Collection and I\'ve made changes to many of its Models. What\'s the best way to save all of the changes using a single HTTP request?

4条回答
  •  天涯浪人
    2020-12-08 07:33

    I'm going to do the Wrong Thing here and quote Wikipedia regarding proper RESTful practices: a PUT to example.com/resources should replace the entire collection with another collection. Based on this, when we had to support editing multiple items simultaneously, we wrote up this contract.

    1. The client sends {"resources": [{resource1},{resource2}]}
    2. The server replaces the entire collection with the new information from the client, and returns the information after it's been persisted: {"resources": [{"id":1,...},{"id":2,...}]}

    We wrote the server half of the contract in Rails, but here's the client half (in CoffeeScript, sorry!):

    class ChildElementCollection extends Backbone.Collection
      initialize: ->
        @bind 'add', (model) -> model.set('parent_id', @parent.id)
    
      url: -> "#{@parent.url()}/resources" # let's say that @parent.url() == '/parent/1'
      save: ->
        response = Backbone.sync('update', @, url: @url(), contentType: 'application/json', data: JSON.stringify(children: @toJSON()))
        response.done (models) => @reset models.resources
    

    I thought this was a lot easier to implement then overriding Backbone.sync. One comment on the code, our collections were always child objects, which should explain why the code sets a "parent_id" whenever an object is added to the collection, and how the root of the URL is the parent's URL. If you have root-level collections that you want to modify, then just remove the @parent business.

提交回复
热议问题