Grails BootStrap: No signature of method: *.addTo* applicable

放肆的年华 提交于 2019-12-12 02:05:15

问题


I have two domain classes: User

class User {

    String username
    String password
    String email
    Date dateCreated
    Date lastUpdated

//  static belongsTo = [profile: Profile]

    static constraints = {
        username size: 3..20, unique: true, nullable: false, validator: { _username ->
            _username.toLowerCase() == _username
        }
        password size: 6..100, nullable: false, validator: { _password, user ->
            _password != user.username
        }
        email email: true, blank: false
//      profile nullable: true
    }
}

and Profile:

class Profile {

    String firstName
    String middleName
    String lastName
    byte[] photo
    Date dateCreated
    Date lastUpdated

    static belongsTo = [User]

    static constraints = {
        firstName blank: false
        middleName nullable: true
        lastName blank: false
        photo nullable: true, maxSize: 2 * 1024**2
    }
}

A profile can belong to only one user and a user can have (or belong to?) only one profile. When I try to create the objects in BootStrap.groovy in the current setup I get an error saying that the addTo() method does not exist. I don't really know what I am doing wrong. This is how I am creating them in BootStrap.groovy:

User arun = new User(username: 'arun', password: 'password', email: 'arun@email.com').save(failOnError: true)
Profile arunProfile = new Profile(firstName: 'Arun', lastName: 'Allamsetty').addToUser(arun).save(failOnError: true)

Can someone please point out the mistake(s). I am sure it's silly.


回答1:


A strict bi-directional one-one relationship is required as you have requested for:

A profile can belong to only one user and a user can have (or belong to?) only one profile

Three modifications are mainly required in domain classes:

//User.groovy
static hasOne = [profile: Profile]

static constraints = { 
    profile unique: true
}

//Profile.groovy
User user

Above is a bi-directianl one-one relationship. You do not need addTo* anymore while creating each of them.

Profile arunProfile = new Profile(firstName: 'Arun', lastName: 'Allamsetty')

User arun = new User(username: 'arun', password: 'password', 
                     email: 'arun@email.com', 
                     profile: arunProfile).save()


来源:https://stackoverflow.com/questions/26351208/grails-bootstrap-no-signature-of-method-addto-applicable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!