Grails clear hasMany条目并添加新的错误?

时间:2013-09-22 12:55:37

标签: grails gorm

我目前正在处理grails应用程序,并且我有一个附加到帐户的地址列表。基本上我想要做的是当编辑帐户时显示所有附加地址的当前列表,然后我可以从视图中删除/添加任意多个。当捕获到这些数据时,它会被控制器拾取,我想要做的是能够清除该帐户中的所有当前地址,然后再次使用视图中存在的内容创建列表,我的代码如下:

帐户域名

class Account {

    String name
    Date dateCreated
    Date lastUpdated

    static hasMany = [addresses:Addresses]

    static mapping = {
        addresses cascade:"all-delete-orphan"
    }

    def getAddressesList() {
        return LazyList.decorate(
              addresses,
              FactoryUtils.instantiateFactory(Addresses.class))
    }

    static constraints = {
        name(blank:false, unique: true)
    }

}

地址域:

class Addresses {

    int indexVal
    String firstLine
    String postcode
    String area

    static belongsTo = [account:Account]

    static mapping = {
    }

    static transients = [ 'deleted' ]

    static constraints = {
        indexVal(blank:false, min:0)
    }


}

帐户控制器:

def update() {

    def accountInstance = Account.get(params.id)
    if (!accountInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'account.label', default: 'Account'), params.id])
        redirect(action: "list")
        return
    }

    if (params.version) {
        def version = params.version.toLong()
        if (accountInstance.version > version) {
            accountInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                      [message(code: 'subscriptions.label', default: 'Subscriptions')] as Object[],
                      "Another user has updated this Account while you were editing")
            render(view: "edit", model: [accountInstance: accountInstance])
            return
        }
    }

    accountInstance.properties = params

    accountInstance.addresses.clear()
    accountInstance.save(flush: true)

    ....

}

错误:

  

拥有实体实例不再引用具有cascade =“all-delete-orphan”的集合:com.tool.Account.addresses。 Stacktrace如下:
      消息:拥有实体实例不再引用具有cascade =“all-delete-orphan”的集合:com.tool.Account.addresses

这个错误似乎是在线控制器中发生的:

accountInstance.save(flush: true)

我已经尝试了几种不同的方式来实现这一点,并且非常感谢一些帮助。

2 个答案:

答案 0 :(得分:9)

所以看起来你已经完成了Grails可以为你做的一些工作。

class Account {

    String name
    Date dateCreated
    Date lastUpdated

    List addresses

    static hasMany = [addresses:Address]

    static mapping = {
        addresses cascade:"all-delete-orphan"
    }

    static constraints = {
        name(blank:false, unique: true)
    }

}

class Address {
    String firstLine
    String postcode
    String area

    static belongsTo = [account:Account]
}

这将产生您希望将地址作为列表的效果。

我找到了

instance.addresses = null

instance.addresses.clear()

为我工作

答案 1 :(得分:-1)

addresses cascade:"all-delete-orphan"班级中定义Account时,static belongsTo = [account:Account]中不需要Addresses。因此,只需尝试删除该语句并测试您的代码。请参阅相关的link