I have a backbone application which, upon load, needs to fetch data from four different collections (Rails–>JSON back end).
That’s four hits to the server, and I’m guessing there’s a better way.
I started out by trying to pass Rails to_json() of the query results into the router initialization in the Rails view such as:
<script type="text/javascript">
$(function() {
window.router = new Backbonedemo.Routers.CalendarsRouter({calendars: [], tasks: <%= @tasks %>});
Backbone.history.start();
});
</script>
but that brought no joy.
So, what’s the correct way to run the equivalent of fetch() at startup, without having to hit JSON for each collection I want to collect?
Check out the rabl gem. It allows you to customize your json response to a much greater degree than regular
to_jsonwill allow.Here’s a basic way to set up a project where you need to deliver a load of JSON up front:
First, set up your controller to pull data on page load, for examlpe
localhost:3000/homewould look in the home controller index:Next, set up a
rabltemplate, this takes the place of a view or a partial, and returns JSON to your client. I’m actually going to use a partial, to make loading into the home/index.html view nice and easy:That’s some relatively fancy rabl that will deliver a bunch of json, including a related set of records, all in one JSON object.
In your html view that loads up backbone, you need to pass the controller’s object to the partial:
To recap:
html.erbview (the one that starts up backbone)rabltemplate that returns strictly JSONThe beauty of this is that you can set up json.rabl responses for any of your controller actions and have them return a variety of json stuff, all easily controllable. The thing I did above is the “difficult” part where you want to load up stuff from many tables into a single JSON call on your first page load–avoiding multiple AJAX/backbone fetch requests.
Make sense? I hope so… : / let me know if anything is unclear.