Lets say Bookshelf has_many :books. I can dump a bookshelf to json, including it’s associated books like this:
@bookshelf.to_json :include => [:books]
But I want a simple ruby hash instead. I’ve tried #attributes but that doesn’t appear to take any arguments. And i’ve tried #to_hash but that method doesn’t on ActiveRecord::Base.
I know I could do this:
JSON.parse @bookshelf.to_json(:include => [:books])
But that feels like a huge and ugly performance waste. I’m sure it’s compiled to a hash internally before its JSON-ified, so I dont want to have to do an extra round of encode/decode for no reason.
In Rails 2.3 you can use
as_json:The
as_jsoncall is very helpful for this situation. It can take attributes and it returns a hash, though the keys are a little odd when you start including nested objects. Specifically, the keys for the current object are all strings, and the key for the handle of the nested object is a symbol.So, for your example, your call could look something like:
hash = @bookshelf.as_json(:include => {:author => {}, :books => {:include => :pages}})And access to the
hashobject would look something like:In Rails 3.0 you can use
serializable_hash:The v2.3
as_jsonfunctionality moved to theserializable_hashmethod. It works the same as the above (looking at the source code you can tell the v2.3as_jsonmethod was moved to the v3.0serializable_hashmethod).