Similar to my last question (Grails databinding: creating instances of an abstract class), I want to use data binding with a class that contains a collection of abstract classes with a hasMany relationship, but in this case, instead of using a List, I'm using a Map.
I created a smalll project with a failing integration test to show the problem that can be found in Github, run it with:
grails test-app -integration -echoOut DataBinding
Anyway, I'll explain the problem by describing the classes and the test here:
class LocalizableContent {
Map contentByLocale = [:].withDefault { locale -> new Text() }
static hasMany = [ contentByLocale : Content ]
}
abstract class Content {
static belongsTo = [ localizableContent : LocalizableContent ]
static constraints = {
localizableContent nullable:true
}
}
class Text extends Content {
String text
}
As you can see, I'm already using the withDefault trick, but apparently it's not being called by Grails / Spring (I even tried to throw an exception in the default closure to verify that the code is not executed).
For the sake of the test, I also created a LocalizableContentController which is empty. With all that, the following integration test then fails:
void testMapDatabinding() {
def rawParams = [ 'contentByLocale[en].text': 'Content' ]
def controller = new LocalizableContentController()
controller.request.addParameters(rawParams)
controller.request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller)
def localizableContent = new LocalizableContent(controller.params)
assert localizableContent?.contentByLocale['en']?.text == 'Content'
}
It says that localizableContent.contentByLocale is a map which looks like ['en': null], so apparently the data binding is understanding the map syntax and trying to create an entry for the 'en' key. But is not trying first to get the entry for that key, since the withDefault is not being called.
The following one tests that the withDefault works fine, and it passes:
void testMapByDefaultWithNoDatabinding() {
assert new LocalizableContent().contentByLocale['en']?.getClass() == Text
}
What am I missing here?