Search code examples
grailsgrails-ormrelationship

Grails addTo* with result of database


Why this code not work fine?

def classeInstrumento = classeInstrumentoService.getClasseInstrumento("value")

def instrumentoInstance = new Instrumento().addToClasseInstrumento(classeInstrumento)

I receive this error message on console:

No signature of method: package.Instrumento.addToClasseInstrumento() is applicable for argument types: (package.ClasseInstrumento) values: [package.ClasseInstrumento : 5]

And this is the Domains structure

class ClasseInstrumento {
    static hasMany = instrumentos: Instrumento
}

class Instrumento {

    ClasseInstrumento idClasseInstrumento

    static hasMany =  [ativoDefs: AtivoDef,
                      futuroDefs: FuturoDef,
                      operacaoDefs: OperacaoDef]

    static belongsTo = [ClasseInstrumento]
}

So I expected that it worked, but it didn't :(

Thanks for the replies!


Solution

  • Instrumento belongsTo ClasseInstrumento.

    which means ClasseInstrumento is the parent and Instrumento is the child of ClasseInstrumento (signified by hasMany in ClasseInstrumento)

    addTo* is used from the parent towards the child which means

    "Add the parent as a foreign_key reference to the child", which means

    classeInstrumento.addToInstrumentos(new Instrumento())

    will work and not the former approach you use.