grails - Better way to discover relationship dynamically when saving a new record? (otherSide fails) -


given relationship:

class {     string name     static hasmany = [b:b] } class b {     string name     static belongsto = [a:a] } 

i have record b want save. i've discovered via working grails reflection (omitted in code example below) needs instance of class b. beyond that, record b knows:

  • it has relation "a"
  • relation "a"'s key

since it's dynamic case, we not know , must discover:

  • relation "a" instance of class a (so can call a.find(a's key))
  • the "other side" of relation - class a's perspective - relation "b" (so can call .addtob(b))

so how save b database? here's how i'm doing it:

class assoctests extends grailsunittestcase {     protected void setup() {         super.setup()         // don't know part, it's in db         def = new a(name:"al")         a.save()     }      void testassociation() {         // want create new b such name="bob"         // had discover "class b" using (working) grails reflection         // omitted example.         def b = new b(name:"bob")         // ... , relation "given" below         def given = [a:[name:"al"]]         // need call a.find([name:"al"]).addtob(b).  "a" ,         // "addtob" unknown need found via reflection         def gdc = new defaultgrailsdomainclass(b)         given.each { give ->             def prop = gdc.getpropertybyname(give.key)             if (prop.isassociation() && !prop.isowningside()) {                 println "i want use otherside, it's ${prop.otherside}"                 def os = reallygetotherside(b, give)                 def object = os.parent.find(                         os.parent.newinstance(give.value))                 object."${os.method}"(b)             }                }                def bfound = b.findbyname("bob")         assertequals "al", bfound.a.name     }      def reallygetotherside(clazz, relation) {         def parent=clazz.belongsto[relation.key]          def addto=parent.hasmany.find { (clazz == it.value) }.key         [parent:parent, method:"addto${addto.capitalize()}"]     } } 

...with otherside returning null, unfortunately. can't best way this, can it?

if understood correctly, can refer these docs here. can try following:

  `new a(name:"gatwick")          .addtob(new b(name:"ba3430"))          .addtob(new b(name:"ez0938"))          .save()` 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -