I am getting some weird behavior when creating models with backbone.js and rails 3.0.7 (and coffeescript).
I create a model with
@model = @collection.create
param : a_param
param : another_param
This saves to rails fine and the return object is what I expect (when I console.log @model it returns a proper looking backbone model with id, cid, attributes…etc).
When I console.log @model.id it returns undefined (Even though it was there in console.log @model).
When I console.log @collection it returns the expected collection, but when I console.log @collection.models it returns an empty array.
When I load the @collection via json in the (rails)page:
( json_from_the_page : #{@collection.to_json} )
@collection = new CollectionName()
@collection.reset options.json_from_the_page
and console.log @collection.models everything works fine so it must be something to do with saving to the server?
Any ideas, or places I should look in the backbone code to further debug?
According to the source code for Backbone, the ID of an object is only set if it receives the ID during construction. Rails is setting the ID, so when you ask for it from rails, you get one, but you don’t get one when you build a new object.
This is by design; backbone assumes that the canonical ID will be set by the server. So for a “freshly made” model, the ID isn’t set automatically (and the model’s method
isNew()returnstrue).If you want the freshly made model to have an ID, save it immediately (and don’t act on it until the save returns) so your server can provide an ID. If you have a programmatic ID that is reliable on the client side, override
initialize()to provide one during construction if one is not provided in the attributes field.