no amount of Googling is managing to solve my confusion so I thought I'd ask the question on here.
I'm trying to save a model and make use of success/error callbacks. On the backbone documentation it states you save your model like so: model.save([attributes], [options])
.
I cannot find anywhere on the documentation that tells you how to save the entire model (i.e. without specifying the attributes), but have come across this question where the second answer says to save the entire model you can do model.save({}, [options])
.
However I am trying this to no avail. My code is below:
Backbone Model:
class Student extends Backbone.Model
url: ->
'/students' + (if @isNew() then '' else '/' + @id)
validation:
first_name:
required: true
last_name:
required: true
email:
required: true
pattern: 'email'
schema: ->
first_name:
type: "Text"
title: "First Name"
last_name:
type: "Text"
title: "Last Name"
email:
type: "Text"
title: "Email"
In my view I have the following function:
class Students extends CPP.Views.Base
...
saveModel = ->
console.log "model before", @model.validate()
console.log "model attrs", @model.attributes
@model.save {},
wait: true
success: (model, response) ->
notify "success", "Updated Profile"
error: (model, response) =>
console.log "model after", @model.validate()
console.log "model after is valid", @model.isValid()
console.log "response", response
notify "error", "Couldn't Update"
In the first console.log before the save I am told that the model is valid, via the means of an undefined
response. If indeed I look at the model I can see that all three fields are filled in.
Similarly in the next two console logs in the error @model.validate()
and @model.isValid()
both return undefined
and true
respectively.
However the response I get from trying to save the model is Object {first_name: "First name is required", last_name: "Last name is required", email: "Email is required"}
Finally in the console.log of the models attributes I get:
Object
created_at: "2012-12-29 23:14:54"
email: "email@email.com"
first_name: "John"
id: 2
last_name: "Doe"
type: "Student"
updated_at: "2012-12-30 09:25:01"
__proto__: Object
This leads me to believe that when I passed {}
to my model it was actually trying to save the attributes as nil, else why else would it have errored?
Could someone kindly point out what I'm doing wrong? I'd rather not have to pass each attribute individually to the save!
Thanks in advance