我正在试图找出如何根据雇主,角色,项目文档ID以及是否经过认证来过滤将进入下拉菜单的用户列表。我只有满足列表中显示的所有要求的用户。我无法正确编译代码。我使用的ifs太多了?有没有更好的方法来写它?感谢您提前提供任何帮助。
我试图通过雇主,角色和来过滤列出的用户 如果他们有积极的证明。
def assign_roles() {
List documentAuthors = []
List fieldTechnicians = []
ProjectDocument projectDocument = ProjectDocument.get(params.id)
Project project = Project.get(params.projectId)
User authUser = docRegService.authenticatedUser
def published_document = CertificationHistoryHeader.findAllByUserAndPublishedDocument(user, published_document)
String employerAdminCertifier = CertifierDocument.findByDocument(projectDocument ? .document ? .document) ? .certifier.name
EmployerUser.findAllByEmployer(authUser.employer) * .user.each {
User user - >
if (CertifierDocument.findByDocument(projectDocument ? .document ? .document) ? .certifier.name == employerAdminCertifier) {
if (latest.action in [CertHistoryActions.CERTIFIED.toString(), CertHistoryActions.RE_CERTIFIED.toString()])
if (user.hasRole(Roles.ROLE_DOCUMENT_AUTHOR.toString())) {
documentAuthors.add(user)
}
if (user.hasRole(Roles.ROLE_FIELD_TECH.toString())) {
fieldTechnicians.add(user)
}
}
}
答案 0 :(得分:1)
嗯,你确实有语法错误。您不能在安全导航操作符(?。),扩展运算符(*。)中使用空格,也不能在声明闭包参数( - >)时使用空格。至于更好的写作方式,这里是我的看法版本:
def assign_roles() {
List documentAuthors = []
List fieldTechnicians = []
ProjectDocument projectDocument = ProjectDocument.get(params.id)
Project project = Project.get(params.projectId)
User authUser = docRegService.authenticatedUser
def published_document = CertificationHistoryHeader.findAllByUserAndPublishedDocument(user, published_document)
String employerAdminCertifier = CertifierDocument.findByDocument(projectDocument?.document?.document)?.certifier.name
def isValidAction = latest.action in [CertHistoryActions.CERTIFIED.toString(), CertHistoryActions.RE_CERTIFIED.toString()]
if(CertifierDocument.findByDocument(projectDocument?.document?.document)?.certifier.name == employerAdminCertifier)) {
EmployerUser.findAllByEmployer(authUser.employer)*.user.each { User user ->
def roles = EmployerUser.where {
/*
* A query to get all of the user's roles.
* This will depend on how EmployerUser and role domain classes are associated.
* The list can be limited to the two roles you're looking for.
*/
}.list()
if(isValidAction && roles.contains(Roles.ROLE_DOCUMENT_AUTHOR)) {
documentAuthors.add(user)
}
if(roles.contains(Roles.ROLE_FIELD_TECH)) {
fieldTechnicians.add(user)
}
}
}
}
user
循环中的大部分条件似乎与用户无关,因此我不会为每个用户评估它们,而是执行一次,在循环之前。这本身就清理了循环中条件的使用方式。事实上,如果不满足 employerAdminCertifier 条件,我会跳过整个循环。
然后,我不再调用user.hasRoles()
两次,而是运行查询以获取用户的角色。然后使用结果列表。这减少了数据库调用。