0

我试图以一种可以触发创建新对象的方式检测对集合的更改。例如,一个库存有许多项目。一个项目有一个名称和一个数量。我能够使用脏检查从项目中检测到添加/删除。

//Detecting add/change
inventoryInstance.items.isDirty()

我很难识别关联项目对象(名称、数量)的更改以及项目的订单更改。isDirty() 似乎无法识别这些更改。我正在使用 Grails 1.3.7,并且我正在通过 HTML 表单和索引字段名称(items[0].name、items[0].quantity)使用 grails 数据绑定。有没有人有建议的解决方案或替代方法?

示例域类:

class Inventory {
  List items = new ArrayList()

  static hasMany = [items:Item]
  static constraints = {
    items(size:0..10)
  }
  static mapping = {
    items cascade: 'all-delete-orphan'
  }
}

class Item {
  String name
  Integer quantity = 1
  Boolean deleted = false

  static transients = ['deleted']
  static belongsTo = Inventory
  static constraints = {
    name blank:false
    quantity size:1..100
  }
}

控制器

def inventoryInstance = Inventory.get(params.id)

if( inventoryInstance ) {
  inventoryInstance.properties = params

  // Check for add/removes, this works.
  def isDirty = inventoryInstance.items.isDirty()

  if(!isDirty) {
    // Check items in list for changes, does not work..
    inventoryInstance.items.each { item ->
      if(item.dirtyPropertyNames) isDirty = true
    }
  }

  if(isDirty) {
    //do something...
  }

  inventoryInstance.save(flush:true)
}
4

1 回答 1

0

这是我的代码,其功能类似于您所要求的:

        def taskChanges = []
        requestInstance?.tasks?.each { task ->
            taskChanges << [task,
                    task?.dirtyPropertyNames?.collect {name ->
                        def originalValue = task.getPersistentValue(name)
                        def newValue = task."$name"
                        log.debug "$name : old:: $originalValue , new:: $newValue ."
                        [(name): [originalValue: originalValue, newValue: newValue]] //returned and added to taskChanges list
                    }
            ]
        }
于 2012-05-30T01:54:26.923 回答