Question

I have a class like this:

class Apple extends Fruit {
    static mapping = {
        discriminator "AppleType"
    }
}

Is there any way to get this discriminator value in the controller/view?

Was it helpful?

Solution

You can check the mapping of your domain class with the Mapping class. Example:

def mapping = GrailsDomainBinder.getMapping(Apple)
println mapping.discriminator

OTHER TIPS

As an addition to Sergio's answer, the GrailsDomainBinder, as of 2.3, no longer has the getMapping() method as static. You must instead instantiate a GrailsDomainBinder.

def mapping = new GrailsDomainBinder().getMapping(Apple)
println mapping.discriminator

I've used this hack in the past. Create a derived property on the base class that queries the discriminator column.

static mapping = {
    fruitType formula: "class"  // discriminator column defaults to 'class'
}

String fruitType

This adds a fruitType property that gets set every time the class is pulled from the database.

The property will be null until it is fetched from the db.

If you change your discriminator column, just change the formula accordingly.

static mapping = {
    discriminator column: "custom_column_name"
    fruitType formula: "custom_column_name"
}

String fruitType
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top