Consider two domain classes; Job and Quote.
A Job has many Quotes but a Job also has an accepted quote. The accepted quote is nullable and should only be set once a part
Grails/GORM has made the associations simpler by following the methodology of convention over configuration and making things more verbose.
What do you think of the below structure of the domain
classes?
class Job {
String title
static hasMany = [quotes: Quote]//Job has many Quotes. Note: Accepted Quote is one of them.
}
class Quote {
BigDecimal quoteAmount
Boolean isAccepted
static belongsTo = [job: Job]//Quote always belongs to a Job.
//When a Job is deleted, quote is also cascade deleted.
}
Now if you create your quote like below then everything should work perfectly:
def job = new Job(title: "Test Job").save()
//Just adding a quote
def quoteInstance = new Quote(quoteAmount: amount)
job.addToQuotes(quoteInstance)
job.save()
//Now accepting that quote
quoteInstance.isAccepted = true
job.save()
Done.
Do we need an acceptedQuote
reference in Job? No
How to get to the acceptedQuote?
def acceptedQuote = job.quotes.find{it.isAccepted}