How do I load sub-models with a foreign key relationship in Backbone.js?

元气小坏坏 提交于 2019-12-05 17:48:07

With Tastypie, you can change the response to being a nested object, instead of a link, by specifying full=True in the ForeignKey definition:

class PersonResource(SQLAlchemyResource):
    address = ForeignKey(AddressResource, 'address', full=True)

This returns the address object along with the person.

Next, I still don't know if this is the best way, but I moved my sub-model out of the attributes, and overloaded parse() to set it, and update() to save it, like:

class Person extends Backbone.Model
  address: new Address
  urlRoot: '/api/v1/person/'
  url: -> return @urlRoot+@id+'/?format=json'
  defaults: { name: 'Anon'}

  parse: (response) ->
     addressResp = response.address || {}
     addressAttr = @address.parse(addressResp)
     @address.set(addressAttr)
     return response

  update: (options) ->
     @set('address',@address.toJSON())
     Backbone.sync 'update', @, options

In this example, I could add the address back to the attributes and manage it with set/get, but then in my own environment, I've created an alternate toJSON function for the json to post to the server, and couldn't find a good way to set the json to the object without changing it from a collection to a json response.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!