Search code examples
grailsviewcontrollergspjoin

Rendering joinTables as a list in Grails


I've got two domain classes: Car and Driver. I'd like to make a gsp view that displays the Car and Driver info in a list that looks more or less a default scaffolded list. For example:

Make  Model  Driver  Age
------------------------
Chevy Nova   Joe     20
Chevy Nova   Mike    30
Chevy Nova   Sally   40 

Here's the domain classes:

class Car {
  String make
  String model

  static constraints = { }
  static hasMany = [ drivers : Driver ]

  static mapping = {
    drivers joinTable: [name: 'Car_Driver', column: 'DRIVER_ID', key: 'CAR_ID']
  }
}

class Driver {
  String name
  int    age

  static constraints = { }  
}

Make a car and give it a few drivers:

def car = new Car(make: 'Chevy', model: 'Nova')
def driver1 = new Driver(name: 'Joe', age: 20)
def driver2 = new Driver(name: 'Mike', age: 30)
def driver3 = new Driver(name: 'Sally', age: 40)

car.addToDrivers(driver1)
car.addToDrivers(driver2)
car.addToDrivers(driver3)
car.save()

What do I need to do in my CarController and/or gsp view to make a joined list happen (and still work with pagination)?


Solution

  • If a Driver can have only one Car, you need a Driver to reference Car and just to render scaffolding list for a Driver.

    To tweak list columns, you'll have to grails generate-views.

    If a Driver can have many Cars, and you don't want to pull Car_Driver table into visible domain model (it has no own domain meaning), make a scaffolding-like list action using SQL query result as a cardriverInstancesList. Like here: SQL/Database Views in Grails.

    Just check that result is a PagedResultList. If not, you can create a PagedResultList by hand, it is easily constructed from a List and totalCount, which you can find with SQL.