views:

46

answers:

1

I have a hash object from an ActiveRecord. I'm going to be calling to_json on it, but I am looking to reduce the depth of the object that is being returned. Here is what my find looks like:

@tags = Tag.find_all_by_type("some_type", :select => :name)

The result of @tags.to_json looks like this:

[{"tag": {"name": "some tag name"}},
 {"tag": {"name": "another tag name"}},
 {"tag": {"name": "etc..."}}]

However, I want the result to look like this since I don't need each object wrapped in a tag object:

[{"name": "some tag name"}, {"name": "another tag name"}, {"name": "etc..."}]

Is there a way I can do this through a map, collect, or similar call?

+2  A: 

If you set the variable ActiveRecord::Base.include_root_in_json to false, you will get the behavior you are looking for.

Reference

huntaub
Thanks, that worked. Although it's probably not the right thing to do, I set the value in the specific view where I need this to happen. I didn't want to negatively effect any other calls in the project where others might expect the root in JSON.
Matt Huggins
That's true. I would recommend changing it back to the default of 'true' when you are done with your non-root JSON.
huntaub
Tag.include_root_in_json = false # Less chance of messing up other code. I really wonder why they didn't just let you specify this in the option hash passed to the #to_json method.
Lars Haugseth
Nice find Lars, that is definitely a much better idea than to set the global. And, it does seem like that should be an option.
huntaub