Search code examples
grailsgrails-ormgrails-2.0grails-domain-classgrails-controller

Grails Class with hasMany


I have this domain class that has a one-to-many relationship as with dynamic scaffolding show below:

Domain:

package mienapp

class Announcements {
    String user
    String title
    String comments
    Date dateCreated


    static hasMany = [tag: Tags]

    static mapping = {  
       comments sqlType: 'text'
    }

    static constraints = {
    }
}

Controller:

package mienapp
class AnnouncementsController {
  def scaffold = true
  def index() { 
     redirect(action: list)
  }
}

When controller redirects to list, the table shows all fields defined in announcements class. How can I show the value of field from tags in the table as well?


Solution

  • Assuming your list method returns a model with an Announcements instance as

    def list() {
      ..    
      [announcementsInstance: announcementsInstance, ...]
    }
    

    in your view, you can access tags like so

    <g:each in="${announcementsInstance.tag}" var="tag">
      ${tag.someproperty}
    </g:each>