Benito Serna Tips and tools for Ruby on Rails developers

Your API in your Views, using Jbuilder

June 3, 2012

When I initialize a Backbone or a Javascript app, in a Rails view, I like to populate the template with the records that I am going to need. This is because if I dont populate this records in the view, then I have to fetch the record in the javascript app, so I need another call to the server :(.

I think a good way to produce, your JSON objects is with Jbuilder, because in this way you don’t have to override the “as_json” method. Then if you have a template that returns JSON, you can render it in your view.

The example

json.array!(@milestones) do |json, milestone|
  json.(milestone, :id, :name, :due_date)
  json.tasks milestone.tasks
end
<%= content_tag "div", class: "milestones",
  data: {
    milestones: render(template: "api/v1/milestones/index.json")
  } do %>

  <%= javascript_tag do %>
    jQuery(function(){
      App.init();
    });
  <% end %>
<% end %>

Related articles

Weekly tips and tools for Ruby on Rails developers

I send an email each week, trying to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or All post by topic.