Getting Backbone.js to Sync With Rails and Mongoid

I have started working with Rails, Backbone.js and mongoDB. I chose Mongoid as the ODM to handle all of my ActiveModel needs within my Rails app. The biggest challenge I ran into, with this configuration, was trying to get all of the syncing functionality working between Backbone.js and Rails.

Fortunately, the URL scheme that Backbone.js uses for syncing data matches perfectly with Rails’ Resource Routing. However, this relies on the JSON that is sent to a Backbone.js model to have a property of id. But the JSON that is emitted form Rails/Mongoid/mongoDB does not have that property. It has an _id property to represent the id of the document.

I have found two ways to solve this problem. First, as this blog post suggests, you can modify the JSON that is emitted. I don’t care for this approach, because this then modifies the every request for JSON, unless you override what you have already overridden. I prefer the approach of letting Backbone know how to interpret your data.

This can be done by setting the idAttribute property within you model to "_id", see the example below.

Set the idAttribute on a Backbone model
1
2
3
var Sidebar = Backbone.Model.extend({
  idAttribute: '_id'
})

Once you have set this in your Backbone.js model, all of the syncing functionality works as expected. Also, when you need to access the id property of your Backbone.js model it works with the id property that is provided by backbone. This setting is not documented on the main Backbone.js page, but you can find it in the annotated source code here.

Comments
« Keeping an eye on productivity I'm going to write a book! »

Comments