I have a rails app using backbone, but when I call save, the server is redirecting to login – even though I’m already logged in (the page on which the backbone model is found is only shown after logging in).
I’m using backbone.matroyshka for nested models – but removing it doesn’t solve the problem.
Here’s the code that calls save on the model in the view:
var view = this;
// save model
this.model.save(null, {
success: function(model, response) {
view.$('#saving').hide();
view.notice('Saved!', 'success');
},
error: function(model, response) {
view.$('#saving').hide();
view.notice(response, 'error');
console.log('save failed ' + response, view.model.get('url'));
}
});
Prior to the model.save request, there is an AJAX request to retrieve data using jQuery AJAX:
$.ajax({
type: 'GET',
url: serverUrl,
data: { url: model.get('url') },
dataType: "json",
context: this,
success: function(data) {
model.set(data);
},
error: function(xhr, status, error) {
console.log('lookup share url failed ' + error, this.get('source'), this.get('about'));
this.trigger('load:fail');
if (options.error) {
options.error(this, error);
}
}
});
The model.save receives a 302 found from the server, redirecting it to the login page.
The controller for the resource is protected by
before_filter :signed_in_user, only: [:create]
signed_in_user is in a session helper taken straight from a tutorial on using omni_auth
def signed_in_user
unless signed_in?
store_location
redirect_to login_path, notice: "You must be logged in to find out what they do."
end
end
I have another page that saves with AJAX (not backbone), and it works fine (also requires a signed in user).
I don’t have much experience with Backbone but it sounds like it’s not sending the CSRF token.
This article should be helpful:
http://ngauthier.com/2011/02/backbone-and-rails-forgery-protection.html