Search code examples
grailsgroovygsp

Creating multiple records in grails


Can anyone tell me how to create multiple records in grails.

This class is in my domain (OperationLog.groovy)

class OperationLog {

    int x, y
    String text
    Validator validator;
    Date oDate = new Date();
    static optionals = ["oDate" ];

    static belongsTo = [Validator]
}

I just want to be able to click on create button to create 1000 objects and when I click on OperationLog List button, I want to see these 1000 records.

and this piece of code belongs to Controllers (OperationLogController.groovy)

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [operationLogInstanceList: OperationLog.list(params), operationLogInstanceTotal: OperationLog.count()]
    }

    def create = {
        def operationLogInstance = new OperationLog()
        operationLogInstance.properties = params
        operationLogInstance.validator = Validator.get(params.validatorId)
        operationLogInstance.operation = Operation.get(params.operationId)
        return [operationLogInstance: operationLogInstance]
    }

    def save = {

        def operationLogInstance = new OperationLog(params)
        println(params.validator)
        operationLogInstance.validator = Validator.get(params.validator.id);
        if (operationLogInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'operationLog.label', default: 'OperationLog'), operationLogInstance.id])}"
            redirect(action: "show", id: operationLogInstance.id)
        }
        else {
            render(view: "create", model: [operationLogInstance: operationLogInstance])
        }
    }

This code creates only one each at a time and this is how view looks like

http://dl.dropbox.com/u/38860715/scr.png


Solution

  • The same way you do anything multiple times, i.e. with a loop or a closure that is executed multiple times, for example:

      def save = {
        1000.times {
          def operationLogInstance = new OperationLog(params)
          println(params.validator)
          operationLogInstance.validator = Validator.get(params.validator.id);
          operationLogInstance.save(flush: true)                   
        } 
        redirect(action: "list")
      }