Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I'm having an issue nesting resources, during serialisation due to the recursive structure of my data. I'm using AngularJS-Rails-Resource for my serialization. I can't tag this post as such because I do not have the reputation required. The github repo for the library is located at: https://github.com/FineLinePrototyping/angularjs-rails-resource

I have two models say, Person and Hat. A person has many hats, and each hat belongs to a person.

In my case I have some special hat-specific logic that requires details of the person the hat belongs to. I'm using a coffeescript class to encapsulate this functionality.

class Hat extends RailsResource
  @configure
    url: api + '/people/{{personId}}/hats/{{id}}'
    name: 'hat'

  label: ->
    "#{person.name}'s #{hat.type}"

But I'm requesting data at the Person level, so when I request Person.get() I need to initialise the person for each hat, as on my API the hat only stores and serialises the person_id/personId

.factory("Person", (railsResourceFactory, railsSerializer, api) ->
  Person = railsResourceFactory
  url: api + '/people',
  name: 'person',
  serializer: railsSerializer( ->
    @resource "hats", "Hat"
  )
  # disclaimer: my actual code checks whether the response is an array and handles errors, but it's not relevant here.
  Person.afterResponse (person) ->
    hat.person = person for hat in person.hats

So now my CoffeeScript class's Hat instances will have access to their persons for their label function.

However, now, on deserialization I get a recursive error due to Hat -> Person -> Hats -> Hat -> Person -> ... etc.

I tried using exclude on "person" in the Hat's serializer but it didn't do anything unless I changed this within the AngularjsRailsResource library

Serializer.prototype.isExcludedFromDeserialization = function (attributeName) {
    return false;
};

to this:

Serializer.prototype.isExcludedFromDeserialization = function (attributeName) {
    return this.exclusions.hasOwnProperty(attributeName);
};

But I get the impression that that's not a bug in the library and it's behaving as intended, I'm just doing it wrong.

How do I handle this? Is there a clean way to remove the person object from the hat before deserializing and then have it re-added? Or have it ignored during deserialization?

Cheers.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.