Hey guys, I need to output my model as json and everything is going well. However, some attributes must be “decorated” by filtering them using some helper methods, such as number_to_human_size. How can i do this?
In other words, let's say that I have an attribute with a name bytes, and I want to pass it through number_to_human_size, and this result will be output in json.
I would also like to "crop" what will be output as json, if possible, since I only need some attributes. Is it possible? Can someone please give an example? I would be very grateful.
Preliminary search results hint at something relative as_json, but I cannot find a tangible example regarding my situation. If this is really a solution, I would really appreciate an example.
Research . It seems I can use the options to_jsonto explicitly indicate which attributes I want, but I still need to figure out how to “decorate” or “filter” certain attributes by passing them through a helper before they are displayed as json.
Will I create a partial for one json model, so _model.json.erb, and then create another one for the action that I use, and inside that just make it partial with a collection of objects? It looks like a bunch of hoops to slip through. I am wondering if there is a more direct / raw way to change the json representation of the model.
source
share