constructor - Is there a better way to set relationships in Grails? -


i'm starting learn grails, might noob question. doubt simple, although i've searched , not find asnwer i'm looking for.

here's problem:

i have domain class has relationship domain class have, this:

class class3 {      static belongsto = [class1:class1]      (...) } 

and i'm creating action inside controller, receives json object class3. inside json, have id of class1 object of mine.

the question is: how create instance of class3, initilizing it's class1 property, having class1's id , not actual instance of it?

i'm can forclass1.get(parsed_id) (that's i'm doing now, , it's working):

def jsonobj = request.json  def class3 = new class3(class1: class1.get(jsonobj.class1.id) (...)) class3.save(flush: true) 

this json looks like:

{class1:{id:1} (...)} 

but think it's little overhead in db instance of class1 initialize class3 relationship , save in db. there better way this? like, save foreign key of class1 inside class3 direcly in db, without select ?

or maybe has way of initializing object json object?

i'm not sure you're doing on json side of things, generally, pretty easy. basic following. let's want create new address belonging specific user:

<form>   <input type="hidden" name="user.id" value="${user.id}" />   <label>street:</label>   <input type="text" name="street" />   .... </form> 

when submit above form, controller might this:

class addresscontroller {     def save() {      def address = new address(params)      address.save()    } } 

when form passed controller, passes in map of params, 1 of is:

user.id: 1234 

because of this, grails automatically set instance of user id of 1234 on address object. when do:

address.save() 

the belongsto relationship has been established.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -