0
votes

I am pretty new to Grails/groovy and looking for a optimized way to write a code.

Domain class:

class Visitors {
    int ID;
    String destination;
    String status; // Status can be OK, FAIL, DONE, REDO, NEW, LAST, FIRST
    .........
    ..........
}

Now in a controller:

class VisitorsController {

    def getVisitors() {
        Visitors.findAllByStatus().each { } // This is where i have confusion
  }
}

At the commented line above, i want to get all Visitors objects that doesn't have status = OK and then go through a loop and update there status = REDO.

The statuses are defined in another class:

public enum VisitorsStatusEnum { NEW, OK, FAIL, DONE, REDO, LAST, FIRST }

Any suggestions?

1

1 Answers

3
votes

With minor modifications to enum and using where query instead of findAllBy would yield expected result.

//src/groovy
enum VisitorsStatusEnum { 
    NEW('NEW'), OK('OK'), FAIL('FAIL'), 
    DONE('DONE'), REDO('REDO'), LAST('LAST'), FIRST('FIRST')

    private final String id

    private VisitorsStatusEnum(String _value) { 
        id = _value 
    }

    String getId() { id }
}

// Domain class
class Visitors {
    Integer ID
    String destination
    VisitorsStatusEnum status
}

//Controller
class VisitorsController {
    def getVisitors() {
        def query = Visitors.where { 
            status != VisitorsStatusEnum.OK 
        }

        // Prefer batch update instead
        query.updateAll( status: VisitorsStatusEnum.REDO )

        render 'Updated'
    }
}