Background:
I use \"rails g scaffold hotel name stars:integer\" to start fast (and insert into the database some records), and write a Backbone client
you've set up your rails code so that it requires a call to /hotels.json
in order to return json, but your backbone code is calling /hotels
only.
the easiest way to fix this is to have a separate api for json data, than for html pages. for example: /hotels
returns html and /api/hotels
return json. see Ryan Bate's Railscasts for an example of this (paid) http://railscasts.com/episodes/323-backbone-on-rails-part-1
another option would be to change your Backbone models / collections so that they append the ".json" to the end of your urls. for example:
Backbone.Model.extend({
url: function(){
var url;
if (this.isNew()){
url = "/hotels/" + this.id + ".json";
} else {
url = "/hotels.json";
}
return url;
}
});
There are likely other options as well. These are just two that came up off the top of my head.
The important thing to understand is that best practice in Rails is NOT to use the Accept headers. There is a nice writeup here that explains why in glorious detail. Summary is browser implementation of HTTP Accept headers is broken. Rails best practice is to set the :format parameter in the request. However, if you like the accept headers they are supported but the rules around what is a valid accept header in rails can be tricky. If your accept header matches the following regex:
BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
then rails throws it away and defaults to text/html mime type. I know, right? Your header happens to match this. The reason most people don't have this problem is that rails "fixes" the default jquery behavior in the rails jquery-ujs. They set a ajaxSetup beforeSend callback in JQuery that puts the */*
at the beginning of the header, which is what the magic rails regex wants to see though I can't really tell why, other than they know that an unmodified browser request will always put it there. Here is how you might fix your accept header in JQuery.
$(function() {
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.setRequestHeader("accept", "application/json");
}
});
});
When your javascript application runs on a different domain, port or protocol than your server, strange things will happen. This is called Same Origin Policy. Just load the javascript from your rails server and everything will be fine.