After reading the official Grails manual, I had a question about how to relate to many-to-one relationships.
When I define two classes: Face and Nose, as follows:
class Face {
String name
Nose nose
static constraints = {
}
}
class Nose {
String color
static belongsTo = [face: Face]
static constraints = {
}
}
I think we can make a Face instance in two ways:
Face creation with nose at the same time
def rudolph = new Face(name: 'Rudolph', nose: new Nose('color': 'Red')).save(failOnError: true)
Creating a nose and face in sequence
def nose = new Nose(color: 'Red').save(failOnError: true)
def rudolph = new Face(name: 'Rudolph', nose: nose).save(failOnError: true)
However, both give me an error, for example:
Fatal error running tests: Validation Error(s) occurred during save():
- Field error in object 'relationship.Nose' on field 'face': rejected value [null]; codes
Of course, if I put restrictions on the nose, it works:
class Nose {
String color
static belongsTo = [face: Face]
static constraints = {
face nullable: true
}
}
I'm not sure if the back reference property should always be NULL or not.
Another question is that the following static property works because it does not have a "face" property:
static belongsTo = Face
If it does not have a property name for the link, why do we define the propertyTo property?