Grails:通过父对象在子对象列表中关联对象

时间:2014-03-27 15:52:57

标签: grails gsp

我有三个对象。

class Registrant {
  String firstName
  String lastName

  List<EventRegistration> events = [].withLazyDefault { new EventRegistration() }

  static hasMany = [
    events: EventRegistration
  ]
}

class EventRegistration {
  static belongsTo = [ registrant : Registrant ]
  Event event
  Integer numberOfTickets
}

class Event {
  String title
}

事件从数据库中融化为表格。

注册人应该能够注册他们希望收到的门票数量的活动。我将这样的表单设置为:

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th># of Tickets</th>
    </tr>
  </thead>
  <tbody>
    <g:each var="event" in="${Event.list()}" status="s">
    <tr>
      <td>${event.title}</td>
      <td><g:field type="text" name="registrant.events[${s}].numberOfTickets"/>
      <g:field type="hidden" name="registrant.events[${s}].event.id" value="${event?.id}"/></td>
    </tr>
    </g:each>
  </tbody>
</table>

控制器代码:

@Transactional(readOnly = true)
class RegistrantController {

  def index() {  
  }

  def load(Registrant registrant){
    render(view: "load", model:[registrant:registrant])
  }

  @Transactional
  def save(Registrant registrant) { 

    println registrant?.events

    if (registrant == null){
      flash.message = "registrant.save.not.found"
      render view:'index'
      return
    }

    if (registrant.hasErrors()) {
      flash.message = "registrant.save.errors"
      render view:'index', model:[registrant:registrant]
      return
    }

    if (registrant.save(flush:true)) {
      redirect action: "load", id:registrant.id 
    }
    else {
      flash.message = "registrant.save.errors"
      render view:'index', model:[registrant:registrant]
      return
    }
  } 
}

这不能保存。有没有办法将事件与EventRegistration相关联,以便注册人可以保存它?

1 个答案:

答案 0 :(得分:0)

由于控制器中绑定的范围是注册人,因此您无需在事件元素前加上注册人。从标签中删除它,绑定将起作用。

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th># of Tickets</th>
    </tr>
  </thead>
  <tbody>
    <g:each var="event" in="${Event.list()}" status="s">
    <tr>
      <td>${event.title}</td>
      <td><g:field type="text" name="events[${s}].numberOfTickets"/>
      <g:field type="hidden" name="events[${s}].event.id" value="${event?.id}"/></td>
    </tr>
    </g:each>
  </tbody>
</table>