Skip to content

Instantly share code, notes, and snippets.

@clouddueling
Created June 14, 2014 17:33
Show Gist options
  • Save clouddueling/70cee9b67077bd93b228 to your computer and use it in GitHub Desktop.
Save clouddueling/70cee9b67077bd93b228 to your computer and use it in GitHub Desktop.
Through association with SailsJS. Make sure all references to models are lowercase because that is how they're stored.
module.exports = {
tableName: 'account_roles',
attributes: {
account_id: 'integer',
name: 'string',
description: 'text',
deleted: 'boolean',
users: {
collection: 'user',
via: 'accountRoles',
through: 'accountroleuser'
}
}
};
module.exports = {
tableName: 'account_role_user',
tables: ['users', 'account_roles'],
junctionTable: true,
attributes: {
id: {
primaryKey: true,
autoIncrement: true,
type: 'integer'
},
users: {
columnName: 'user_id',
type: 'integer',
foreignKey: true,
references: 'user',
on: 'id',
via: 'accountroles',
groupBy: 'user'
},
accountRoles: {
columnName: 'account_role_id',
type: 'integer',
foreignKey: true,
references: 'accountrole',
on: 'id',
via: 'users',
groupBy: 'accountrole'
}
}
};
module.exports = {
tableName: 'users',
attributes: {
name: 'string',
password: {
type: 'string',
minLength: 4,
required: true
},
bio: 'string',
email: {
type: 'email',
required: true
},
cloudinary_public_id: 'string',
accountRoles: {
collection: 'accountRole',
via: 'users',
through: 'accountroleuser'
}
}
};
@levity
Copy link

levity commented Oct 29, 2014

Thank you for this!

@levity
Copy link

levity commented Oct 30, 2014

Have you experienced any issues with this in which you get duplicate records? (e.g. https://gist.github.com/levity/02052edd445b68174c1e) Thanks for any help you can offer!

@navdeepsingh
Copy link

navdeepsingh commented Sep 29, 2016

Hello!! Following not works, in associated table, no records being added.

User.create(params).populate('roles').exec(function createUser(err, user){
            if(err) {
                return res.json(err);
            }
            Role.findOne({name : 'super'}).then(function(role) {
                        user.roles.add(role.id);
                user.save(function(err){
                    console.log(role.id);
                    if (err) { return res.serverError(err); }
                    return res.ok();
                });
            })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment