Created
August 18, 2012 17:04
-
-
Save mde/3388411 to your computer and use it in GitHub Desktop.
Associations for JS Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// User, hasOne Profile | |
var u = User.create({ | |
login: 'asdf' | |
, password: 'zerb' | |
, confirmPassword: 'zerb' | |
}); | |
// Owner has to be saved to add an association | |
u.save(function (err, data) { | |
if (err) { | |
throw err; | |
} | |
User.load(u.id, {}, function (err, data) { | |
var user = data | |
, profile; | |
if (err) { | |
throw err; | |
} | |
profile = Profile.create({}); | |
// Use 'set' + singular model-name to make the association | |
user.setProfile(profile); | |
// Saving the owner saves all the unsaved association-objects | |
user.save(function (err, data) { | |
if (err) { | |
throw err; | |
} | |
// hasOne -- use 'get' plus the singular model-name | |
user.getProfile(function (err, data) { | |
assert.equal(profile.id, data.id); | |
if (err) { | |
throw err; | |
} | |
next(); | |
}); | |
}); | |
}); | |
}); | |
// User, hasMany Accounts | |
var u = User.create({ | |
login: 'asdf' | |
, password: 'zerb' | |
, confirmPassword: 'zerb' | |
}); | |
// Owner has to be saved to add an association | |
u.save(function (err, data) { | |
if (err) { | |
throw err; | |
} | |
User.load(u.id, {}, function (err, data) { | |
var user = data | |
, account; | |
if (err) { | |
throw err; | |
} | |
// Use 'add' + singular model-name to make the association | |
// Eventually this should also take an array to do it in one go | |
user.addAccount(Account.create({})); | |
user.addAccount(Account.create({})); | |
// Saving the owner saves all the unsaved association-objects | |
user.save(function (err, data) { | |
if (err) { | |
throw err; | |
} | |
// hasMany -- use 'get' plus the plural model-name | |
user.getAccounts(function (err, data) { | |
assert.equal(2, data.length); | |
if (err) { | |
throw err; | |
} | |
next(); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment