Grails BootStrap:没有方法签名:* .addTo *适用

时间:2014-10-14 01:11:52

标签: grails groovy grails-domain-class

我有两个域类:用户

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
    }
}

和个人资料:

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
    }
}

个人资料只能属于一个用户,而用户只能拥有(或属于?)一个个人资料。当我尝试在当前设置中的BootStrap.groovy中创建对象时,我收到一条错误消息,指出addTo()方法不存在。我真的不知道自己做错了什么。这就是我在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)

有人可以指出错误。我确定这很傻。

1 个答案:

答案 0 :(得分:1)

如您所要求的那样,需要严格的双向一对一关系:

个人资料只能属于一个用户,而用户只能拥有(或属于?)一个个人资料

域类中主要需要进行三次修改:

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

static constraints = { 
    profile unique: true
}

//Profile.groovy
User user

以上是双向关系的双向关系。在创建每个文件时,您不再需要addTo*

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

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