How is it possible to combine a request into two different domains (w. has-many /belongs-to relationship)

5 views
Skip to first unread message

Mark Nellemann

unread,
Apr 16, 2015, 9:21:49 AM4/16/15
to gra...@googlegroups.com
Dear Grails users,

Looking for advice :)

I am trying to accomplish this: Submit a form with text-field “subject” and text-area “content”, which (if validated) creates 1 new Ticket and 1 Article that belongs to the Ticket just created.

I think I need to create a Command Object w. the combined properties (for validation), but how do I persist the command object into Ticket and Article ?


Simplified, I have the following domains;

# Domain Class: Ticket
class Ticket {
     String title  // Should be set to the subject of 1st Article when saved
     static hasMany = [ articles: Article ]
     static constraints = {
          title(maxSize: 128)
     }
}

# Domain Class: Article
class Article {
     String subject
     String content
     static belongsTo = [ ticket: Ticket ]
     static constraints = {
          subject()
          content()
     }
}



Help is greatly appreciated,

Mark

Søren Berg Glasius

unread,
Apr 17, 2015, 12:50:11 AM4/17/15
to Mark Nellemann, gra...@googlegroups.com
Hi Mark,

if your params contains:

params.title
params.subject
params.content

you could do

class SomeController {
    def save(Article article) { // This would instantiate an Article object and bind content & subject
         def ticket = new Ticket(title: params.title)
         ticket.validate()
         if(article.hasErrors() || ticket.hasErrors()) {
                render(view: 'create', model: [articleInstance: article, ticketInstance: ticket]
                return
         }
         article.save()
         ticket.addToArticles(article)
         ticket.save(flush: true)
         
         flash.message = "Saved Ticket (title: $ticket.title) with Article (subject: $article.subject)"
         redirect(action: 'show', id: title.id)
   }
}

or something like this.

Hope you can use this as inspiration. Assumption is that you use Grails 2.4.4. Disclaimer: I have not run this code, it's from memory.


Best regards / Med venlig hilsen,
Søren Berg Glasius

40 Stevenson Ave, Berkeley, CA 94708
Mobile: (+1)510 984 8362, Skype: sbglasius
--- Press ESC once to quit - twice to save the changes.

--
You received this message because you are subscribed to the Google Groups "Grails User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to grails+un...@googlegroups.com.
To post to this group, send email to gra...@googlegroups.com.
Visit this group at http://groups.google.com/group/grails.
For more options, visit https://groups.google.com/d/optout.

Mark Nellemann

unread,
Apr 17, 2015, 7:01:26 AM4/17/15
to gra...@googlegroups.com, mark.ne...@gmail.com
Hej Søren,

Thanks, it got me in the right direction :)


Br,

Mark
Reply all
Reply to author
Forward
0 new messages