0

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)?

frgauthier
  • 13
  • 3

1 Answers1

1

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.

Community
  • 1
  • 1
Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91
  • Thanks for the [SQL/Database Views in Grails](http://stackoverflow.com/questions/425294/sql-database-views-in-grails) hint. That will work nicely. I do have another question though. In my example, I have multiple cars, each car can have multiple drivers (1:m). How would I pull the Car_Driver jointable into a visible domain model? That sounds exactly like want I should be doing. – frgauthier Jun 02 '11 at 13:44
  • I meant creating `CarDriver` domain class, mapping it on that table and working with it explicitly. 1. I don't think having this join table in domain model is a good idea, because it violates DDD paradigm - it has no physical sense on its own. Join table is a pure artifact of relational data model limitations. 2. Plus, it will leave you without Grails' methods like `Car.addToDrivers()` - though you can implement those by yourself. 3. Still, it all depends on your requirements and might be not that bad. – Victor Sergienko Jun 02 '11 at 21:03