Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails get any of the children in a hasMany

I have a domain class which has many of another domain class. I want any one of the children and don't care which. Example

class MyDomainClass {
  static hasMany = [thingies:OtherDomainClass]
}

I can do this the stupid way like:

def findOne
myInstance.thingies.each{
  findOne=it
}

But is there a better way like:

def findOne = myInstance.thingies.grabTheMostConvenientOne()
like image 789
Mikey Avatar asked Jun 27 '11 21:06

Mikey


1 Answers

thingies is a Collection, so you have everything from Collection at your disposal.

A simple way you might do this is:

def one = myInstance.thingies.asList().first()

However, you probably want to make sure the collection actually has some elements first. The documentation doesn't explicitly say that first() throws an IndexOutOfBoundsException if the list is empty, but I have a feeling it still might. If that's the case, you probably want:

def one = myInstance.thingies.size() > 0 ? myInstance.thingies.asList().first() : null

Or, if you want to be super-concise at the expense of some readability, you can use this approach (courtesy John Wagenleitner):

def one = myInstance.thingies?.find { true }
like image 148
Rob Hruska Avatar answered Nov 05 '22 11:11

Rob Hruska