views:

41

answers:

2

Hi,

I'm using to_json, and including associations. However, the resulting json object includes all of the methods for the associated objects, even when I ask it to exclude methods.

I've tried these ways of doing it:

render :json => @entries.to_json(:include => {:labels => {:only => [:label_id, :name], :methods => []}})
render :json => @entries.to_json(:include => {:labels => {:only => [:label_id, :name], :methods => :none}})
render :json => @entries.to_json(:methods => [], :include => {:labels => {:only => [:label_id, :name], :methods => []}})

And I get the following object:

"entry": {
    "id" : "1",
    "other property of entry" : "value",
    ...
    "labels" : {
        "0" : {
            "name" : "animals",
            "label_id" : "2",
        },
        "1" : {
            "name" : "furry animals",
            "label_id" : "5",
        },
        "_each" : "... method properties",
        "_reverse" "... method properties",
        etc...
     }
}

So each json object for "entry" is created correctly, the associated labels are included, but I can't get it to omit the methods within "labels".

Any ideas for how to do this correctly?

Thanks.


EDIT:

@nirvdrum, thanks for the suggestion. That doesn't fix it unfortunately.

I've added this to the model

def as_json(options={})
  super(:include => {:labels => {:only => [:label_id, :name]} } )
end

And the controller does this:

render :json => @entries

And the result is the same. Any other suggestions would be appreciated.

A: 

I'm not sure how to do it with to_json, but you should be able to do it easily enough with as_json, which is now the preferred way to customize JSON output.

A more thorough treatment of how as_json and to_json interact can be found on Jonathan Julian's weblog.

nirvdrum
A: 

What does your label object's to_json or as_json look like?

In the past, I've overridden a as_json method, and ignored the options coming in.

If you do this:

def as_json(opts={})
  super(:include=>[:name, :address])
end

then the params will be ignored completely. To combat the problem, you could:

def as_json(opts={})
  opts.merge!(:include=>[:name, :address])
  super(opts)
end

Just a shot in the dark. Let me know if that's even in the right vicinity.

Jesse Wolgamott