I have a Backbone application running on a log of rails. I have an Invitation resource, and I can send invitations by sending a POST request for the action of the invitation controller action.
My Backbone model looks like this (coffeescript):
class Invitation extends Backbone.Model urlRoot: '/invitations'
The following is a form template for sending an invitation. I tried to make this as close as possible to conventional rail forms, as it seems that Rails will handle this best of all:
<form action="/invitations" accept-charset="UTF-8" id="new_invitation" class="new_invitation" method="post"> <input id="invitation_recipient_name" class="invitation_recipient_name" type="text" name="invitation[recipient_name]" /> <input id="invitation_recipient_email" class="invitation_recipient_email" type="text" name="invitation[recipient_email]" /> <input type="submit" class="btn primary" name="commit" id="invite" value="Send Invitation" /> </form>
Here is my Backbone View for this model and template.
class InvitationView extends Backbone.View
The problem is that when I click the submit button and the sendInvite method is sendInvite , my server receives data with the following structure:
Parameters: {"recipient_name"=>"A name", "recipient_email"=>" name@example.com ", "invitation"=>{"recipient_email"=>" name@example.com ", "recipient_name"=>"A name"}}
Now it really works, since my invitations#create action involves working with form parameters: params[:invitations] , this is the standard for rails. However, the fact that the name and email address are sent twice in the request seems like a sign that something is wrong with my setup.
Am I doing something wrong or is it right?
Here is my controller action if someone wants to see it:
Change This looks like my invitation model if I set the attributes and write them right before saving:
Invitation _changed: false _changing: false _escapedAttributes: Object __proto__: Object _previousAttributes: Object recipient_email: " dave@example.com " recipient_name: "Dave" __proto__: Object attributes: Object recipient_email: " dave@example.com " recipient_name: "Dave" __proto__: Object cid: "c17" __proto__: ctor
This log is generated by the following btw code:
sendInvite: (e) -> e.preventDefault() name = @$('#invitation_recipient_name') email = @$('#invitation_recipient_email') @model.set recipient_name: name.val(), recipient_email: email.val() console.log "THe model to save", @model
Edit 2
This is how I create my view in my router. How can I change this so that Backbone automatically tracks my model attributes even if I do not receive and install them from the server?
var TeamRouter = Backbone.Router.extend({ routes: { 'members': 'members' }, members: function() { @invite = new MoveOutOrg.Models.Invitation(); @inviteView = new MoveOutOrg.Views.InvitationView({ model: @invite }); $('#stage').append(@inviteView.render().el); } });