Question

I have 2 classes and an Enum. One class is a wrapper for the Enum that contains both the enum and its string representation, the other is a User class. The enum defines the type of user. They are set up as follows:

Class User {

    String username
    String password

    String firstName
    String lastName
    String emailAddress
    UserStatus status
    UserType type
    Date dateCreated

    List<UserRole> roles

    static mapping = {
        roles(fetch: 'join')
    }
}

My Enum is as follows:

enum RoleType {
    SUPER_USER('superuser','Super User'),
    SUPPORT_USER('supportuser','Support User'),
    STANDARD('standard','Standard')

    String id
    String name

    RoleType(String id, String name) {
        this.id = id
        this.name = name
    }

    String toString() {
        name
    }
}

and my wrapper class as follows:

class UserRole {

    static belongsTo = [user:User]

    static auditable = true

    RoleType roleType
    String role

    static constraints = {
        role(nullable:false, blank:false)
        roleType(nullable:false, inList:RoleType.values().toList())
    }

    static mapping = {
        sort(role: "asc")
        role(role: IdentityEnumType,sqlType: "varchar(40)")
    }
}

All pretty standard stuff. Now I want to bootstrap a User into the DB:

    User user = new User(
            username:'support@quirk.biz',
            password:'ilovequirk',
            status:UserStatus.ACTIVE,
            type:UserType.QUIRK,
            firstName:'Quirk',
            lastName:'Support',
            emailAddress:'support@quirk.biz'
        )

        UserRole userRole = new UserRole(roleType:RoleType.SUPER_USER, role:RoleType.SUPER_USER.toString())
        user.addToRoles(userRole)

        user.save(failOnError:true)

When it hits the addToRoles line it breaks and gives me the error message:

No signature of method: za.co.hollard.User.addToRoles() is applicable for argument types: (za.co.hollard.UserRole) values: [za.co.hollard.UserRole : null]

But if I throw in some printlns before the addToRoles method - i can probe the freshly created UserRole object and get out exactly the values that it was created with??

Was it helpful?

Solution

I believe you cannot use 'addTo*' unles you have defined the association as a one-to-many mapping via 'hasMany'. In class 'User' replace,

 List<UserRole> roles

with

 static hasMany = [ roles:UserRole]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top