« Return to Thread: saving a one-to-many

Re: saving a one-to-many

by Fred Janon :: Rate this Message:

Reply to Author | View in Thread

I wonder why your controller is named ServiceOrder.groovy and not ServiceOrderController.groovy? I think the requirement is that 'Controller' has to be part of the name, unless that has been dropped in 0.4.x. Did you use the "generate all" or "generate controller" commands?
 
Then
class ServiceOrder {

  static hasMany = [ items : OrderLine ]

===> missing
Set items = new HashSet()
 
Then in the controller just creating and adding an OrderLine to items will trigger the automatic save of both by Hibernate after the controller action retuns
 
Fred
 
On 3/10/07, Corey <corey_s@...> wrote:

I feel like I'm doing this in more of an idiotic, rather than idiomatic
fashion.

I have something called a ServiceOrder, which can contain many line items,
for which I've created an OrderLine. Each OrderLine associates one or more
Products with any particular ServiceOrder.

I'm wondering how to save a ServiceOrder ( one-to-many ) in the most succinct
way possible. Do I save the ServiceOrder first, then simply begin adding
OrderLines, as I do below - or is there a more direct/elegant/fashionable way
of doing this?


.../domain/ServiceOrder.groovy:

ServiceOrder.groovy
  static constraints = {
     contact( nullable : false )
     creditCard( nullable : false )
  }

  Contact contact
  CreditCard creditCard

}

.../domain/OrderLine.groovy:

class OrderLine {

  static belongsTo = ServiceOrder

  /* are the following constraints desired/valid?
  static constraints = {
     serviceOrder( nullable : false )
     product( nullable : false )
  }
  */

  Integer quantity = 1

  ServiceOrder serviceOrder
  Product product

}


.../controllers/ServiceOrder.groovy:

  // am I doing this "correctly"?
  private save = {

     def serviceOrder = new ServiceOrder(
        contact    : new Contact( params ),
        creditCard : new CreditCard( params )
     )
     serviceOrder.save()

     // there should be a loop here, but I'm simplifying for
     // sake of brevity
     serviceOrder.addOrderLine(
        new OrderLine(
           serviceOrder : serviceOrder,
           product      : Product.get( params.productId )
        )
     )
     serviceOrder.save()

     [ serviceOrder : serviceOrder ]

  }




---------------------------------------------------------------------
To unsubscribe from this list please visit:

   http://xircles.codehaus.org/manage_email


 « Return to Thread: saving a one-to-many