我有两个与多对多关系的模型(角色,权限)。有一个权限列表,角色可以有一些权限。我想为角色创建编辑页面,并将权限添加为复选框列表。
编辑模板:
<form>
{{input type="text" placeholder="role name" value=name}}
<br />
{{#each permissions_list}}
<label>
{{input type="checkbox" name="permissions[]"}}{{name}}
</label><br />
{{/each}}
<button {{action 'save'}}>Edit</button>
</form>
模型:
var Role = DS.Model.extend({
agents: DS.hasMany('agent', {async: false}),
name: DS.attr('string'),
permissions: DS.hasMany('permission', {async: true})
});
var Permission = DS.Model.extend({
type: DS.attr('string'),
name: DS.attr('string'),
roles: DS.hasMany('permission', {async: false})
});
编辑角色控制器
export default Ember.ObjectController.extend({
permissions_list: [],
actions: {
save: function() {
return this.get('model').save();
}
},
load_permissions: function() {
this.set('permissions_list', this.store.find('permission'));
}.on('init')
});
问题:
permissions - 权限列表,该角色包含
permissions_list - 数据库中所有权限的列表
答案 0 :(得分:2)
最简单的方法(IMHO)是为复选框创建一个组件:
App.PermissionCheckboxComponent = Ember.Component.extend({
tagName: '',
checked: function(){
var permission = this.get('permission.name');
var rolePermissions = this.get('role.permissions').mapBy('name');
return rolePermissions.contains(permission);
}.property(),
save: function(){
var permissionChecked = this.get('checked');
var role = this.get('role');
var permission = this.get('permission');
var permissions = role.get('permissions');
if(permissionChecked){
role.get('permissions').addObject(permission);
permission.save();
role.save();
}
else {
role.get('permissions').removeObject(permission);
role.save();
}
}.observes('checked')
});
您的组件模板如下所示:
<script type="text/x-handlebars" id="components/permission-checkbox">
{{ input type='checkbox' checked=checked }} {{permission.name}}
</script>
然后,您可以在编辑模板中使用此组件,如下所示:
<h2>Edit Permissions</h2>
<ul>
{{#each role in model.roles}}
<li>{{role.name}}</li>
<ul>
{{#each permission in model.permissions}}
<li>{{ permission-checkbox permission=permission role=role }}</li>
{{/each}}
</ul>
{{/each}}
</ul>
工作解决方案here