0

Normally when I use backbone.js I would apply this sort of patch to nest model attributes the way that Rails expects them:

Backbone.Model.prototype.toJSON = function() { 
  var hashWithRoot = {}; 
  hashWithRoot[this.modelName] = this.attributes; 
  return _.clone(hashWithRoot);
};


App.Models.Card = Backbone.Model.extend({
  modelName:  'card'
});

However, in my current project I'm using Backbone Relational, which is great, but it has its own toJSON override. The result is that I get a circular reference exception in my console:

Uncaught TypeError: Converting circular structure to JSON

Has anyone managed to successfully produce nested JSON for PUT/POST to a Rails backend with Backbone Relational?

EDIT 2:

I created a jsfiddle that shows the collections and models in question - and included some json to bootstrap the app. For some reason (maybe because I'm hungry) I can't get the fiddle to work.

Hopefully that gives a better idea of what I'm trying to do. I'm going to eat then try to fix the fiddle...

Cheers, Stu

Stu
  • 154
  • 1
  • 11

1 Answers1

1

Is it uncouth to be writing a non-answer answer? Because I can’t write comments…

You need to give us more information. I haven’t used Backbone Relational, but I made a fiddle that manages to serialise a model with a HasMany relation. There are some extraneous and incorrect attributes, but no circular structure error.

What relationships are you using? Can you make a fiddle that is more similar to your application’s structure?

Buck Doyle
  • 6,333
  • 1
  • 22
  • 35
  • 1
    Thanks for the response @backspace. From your fiddle I see that it should be possible to achieve without doing anything special. I'll extract the important stuff from my codebase into a jsfiddle and post it if going through that process doesn't highlight the problem! – Stu May 10 '12 at 01:04
  • Hi @buck doyle. I have updated the example with a fiddle that (although broken) - shows all of my models along with bootstrap data... – Stu May 11 '12 at 05:37
  • 1
    It was broken because you didn’t declare the namespace objects before using them. What browser are you using? It was easy for me to figure this out by looking in the console. I [updated the fiddle](http://jsfiddle.net/buckdoyle/YWkHD/16/); the [source for Backbone-relational shows](https://github.com/PaulUithol/Backbone-relational/blob/master/backbone-relational.js#L1240) how to escape circular serialisation problems, but why not just wrap the output of that code? That’s what I’ve done. Also changed to run after page load so the `div` exists to insert the JSON into. – Buck Doyle May 11 '12 at 10:47
  • you are a true gentleman. Thanks for your time on this. Wrapping the output of the Backbone-relational toJSON as you did in your fiddle was the ticket. – Stu May 13 '12 at 23:50
  • oh - and good shout on the console tip for jsfiddle. I hadn't used it before and didn't even think about trying that – Stu May 13 '12 at 23:52