Rails - json.erb template

11,310

I think the best way to do this would be to skip the erb template if you don't absolutely need if for some reason. Then you could do something like this:

items = Item.all
render :json => items.to_json(:only => [:id, :name]), :callback => params[:callback]

You can override the to_json method in your model to add fields or call methods.

Share:
11,310
bokor
Author by

bokor

Updated on June 04, 2022

Comments

  • bokor
    bokor almost 2 years

    I have been trying to figure out a way to customize JSON with special fields, custom formats, etc etc. I have created an as_json and to_xml method in my model to formulate the object how I need. This works well but it is sloppy because some of my helper methods had to move into the model, because I need the formats in the helpers and model. I also think it is sloppy code and makes the model out of control.

    I have been able to get a format with json.erb working but don't think it is working 100% correct either and the callback doesn't append either. Anyone get this working

    Here is what I got so far.

    api calls format.json

    template called is items.json.erb

    <% @items.each do |item| %>
    <%= { :item => { :id => item.id, :name => item.name }.to_json.html_safe  %>
    <% end %>
    

    This works but seems odd. Anyone have suggestions or have a way to do this?

    btw did this for the callback to work

    <%= params[:callback]+"(" if params[:callback]  %>
    <% @items.each do |item| %>
        <%= { :item => { :id => item.id, :name => item.name }.to_json.html_safe  %>
    <% end %>
    <%= ")" if params[:callback]  %>