Friday, November 26, 2010

Grails Bootstrapping Issue

I'm sure this is a newbie issue, but it's interesting to me.

I've created the Race applications from the book, "Getting Started With Grails, 2nd Edition" by Jason Rudolph.  After creating the Runner domain class, I add "package racetrack", then I try to bootstrap some data.



   1:  class BootStrap {
   2:  def init = { servletContext ->
   3:  def jane = new Runner(firstName:'Jane',lastName:'Doe')
   4:  jane.save()
   5:  }
   6:  def destroy = {}
   7:  }

But, when I run the application, I don't get any data populated and no error.

The answer was in #GRAILS-3842.  In order to create the data, you MUST set the values for "ALL PROPERTIES THAT ARE NOT NULLABLE".

So, when you create a new Runner(), you must supply values for all properties or mark the properties as "nullable:true".  Also, there is a new parameter for the save() method, save(failOnError:true).  This will cause the compilation to fail if the save() method in Bootstrap does not work.

Here is the new code:


   1:  class Runner {
   2:   
   3:  static constraints = {
   4:      firstName(blank:false)
   5:      lastName(blank:false)
   6:      dateOfBirth(nullable:true)
   7:      gender(inList:["M", "F"])
   8:      address(nullable:true)
   9:      city(nullable:true)
  10:      state(nullable:true)
  11:      zipcode(nullable:true)
  12:      email(email:true)
  13:  }
  14:  static hasMany = [registrations:Registration]
  15:      String firstName
  16:      String lastName
  17:      Date dateOfBirth
  18:      String gender
  19:      String address
  20:      String city
  21:      String state
  22:      String zipcode
  23:      String email
  24:      String toString(){
  25:          "${lastName}, ${firstName} (${email})"
  26:      }
  27:   
  28:   
  29:   
  30:   
  31:   
  32:   
  33:  class BootStrap {
  34:   
  35:      def init = { servletContext ->
  36:          def jane = new Runner(firstName:'Jane', lastName:'Doe', gender:'F',city:'Atlanta',state:'GA',email:'jane@toto.com')
  37:          jane.save(failOnError:true)
  38:          def joe = new Runner(firstName:'Joe', lastName:'Blow', gender:'M',city:'Atlanta',state:'GA',email:'joe@toto.com')
  39:          joe.save(failOnError:true)
  40:          def larry = new Runner(firstName:'Larry', lastName:'Eisenstein', gender:'M',city:'Lilburn',state:'GA',email:'larrye@toto.com')
  41:          larry.save(failOnError:true)
  42:   
  43:      }  
  44: