4

我目前正在开发一个 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)

我已经尝试了几种不同的方法来让它工作,并且非常感谢一些帮助。

4

2 回答 2

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()

为我工作

于 2013-09-22T19:30:54.797 回答
-1

当您addresses cascade:"all-delete-orphan"Account课堂上定义时,您不需要static belongsTo = [account:Account]in Addresses。因此,只需尝试删除该语句并测试您的代码。见相关链接

于 2013-09-23T08:44:25.430 回答