I'm 2 months into Grails development and have stumbled across this challenge which i can't find a answer to having used books, the grails website and forum searches. I'm hoping someone can help me.
I have 2 domain classes - AccountPackage and AccountPackageFeatures. The idea is that an AccountPackage (eg Gold Account) can have many features. To represent this the AccountPackage domain has an embedded list of AccountPackageFeatures. Here are the two domain classes:
AccountPackage
class AccountPackage {
String name // eg. Gold Account
boolean active // eg. true - account is active
List features = []
static hasMany = [features:AccountPackageFeature]
static constraints = { }
}
AccountPackageFeature
class AccountPackageFeature {
String featureName // eg. "Number of posts allowed"
String featureCategory // eg. "Job Posting"
String value // eg. "10"
static constraints = { }
}
The data is already saved in the database. In my code I have retrieved a particular AccountPackage instance and now I want to look for a specific feature of that AccountPackage. The way I am doing this is to get the features list from the AccountPackage instance, and then iterate through the list until I find the appropriate feature i'm interested in. Code snippet below:
def desiredFeature = null
def desiredFeatureId = 10
AccountPackage pkg = AccountPackage.findByName("Gold Account")
def features = pkg.getFeatures()
for (feature in features) {
if (feature.id == desiredFeatureId) {
desiredFeature = feature
}
}
I am aware this is pretty inefficient... but what is the right to do this in Grails??
Does grails/GORM provide any inbuilt functionality to save me from doing a custom query? Alternatively should I, for example, add a custom method to my AccountPackage domain object called something like getFeatureWithId which takes an ID and then does a custom query to return the desired feature?
Any advice on best practice / the right way to do this would be much appreciated.