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 particular Quote has been accepted by a user. I have the relationships mapped as follows (simplified for the purpose of illustration).
class Job {
String title
Quote acceptedQuote
}
class Quote {
Job job
BigDecimal quoteAmount
}
The resultant tables are exactly what I require (at least aesthetically) but the problem arises when I go and save a Quote. The Quote is saved successfully with a jobId as per the logic in my code but unfortunately the quote's id gets saved in the Job table as the acceptedQuote. Is there anyway to block this cascading association? The code that persists the Quote is fairly basic and looks something like the following;
def quoteInstance = new Quote(job: jobInstance, quoteAmount: amount)
if (quoteInstance.save(flush: true)) {
render view: 'show', model: [quoteInstance: quoteInstance]
break
}
Obviously the jobInstance is passed to the Quote constructor to save an association in the Quote table but I do not know how to prevent the quote Id saving to the job table as the accepted quote. Maybe the GORM strategy I am using will not satisfy these requirements?
Any help would be much appreciated.
This may not be what you are looking for but I would actually model this a little differently - I would have an accepted flag in the Quote
domain:
class Job {
String title
static hasMany = [quotes: Quote]
}
class Quote {
static belongsTo = [job: Job]
BigDecimal quoteAmount
Boolean accepted
}
Then your persistence could look like this:
jobInstance.addToQuotes(new Quote(quoteAmount: 123.34, accepted: false)) //or true
and no worries regarding your original problem.
You could also add a transient and its getter
to the Job
class to get the accepted Quote
class Job {
String title
static hasMany = [quotes: Quote]
static transients = ['acceptedQuote']
Quote getAcceptedQuote() {
return Quote.findByJobAndAccepted(this, true)
}
}