Search code examples
grailsgrails-orm

Trying to create grails domain object with FK relationship


So I'm trying to load a bit of test data in BootStrap.groovy, and I'm having trouble creating an object that has a one-many FK relationship...

These are the domain classes (examples):

class Book {    
     static hasOne = BookCategory
     String name
    }

and...

class BookCategory {
     static belongsTo = Book
     static hasMany = [books : Book]
     String name
    }

and in Bootstrap.groovy:

def romanceCat = new BookCategory(name: 'Romance').save(flush: true)
def horrorCat = new BookCategory(name: 'Horror').save(flush: true)

def firstBook = new Book(name: 'Kujo', category_id: horrorCat).save(flush: true)

The Categories are being created in postgres, but the book is not. I suspect I don't have the correct syntax for referencing the FK in my new Book(), but I can't seem to find a similar example and have tried several variations. ie. BookCategory: horrorCat, BookCategory.id: horrorCat, etc.


Solution

  • You need to define the name of your BookCategory attribute in Book:

    class Book {
      static hasOne = [bookCategory:BookCategory]
    }
    

    And your Bootstrap should be:

    def romanceCat = new BookCategory(name: 'Romance').save(flush: true)
    def horrorCat = new BookCategory(name: 'Horror').save(flush: true)
    
    def firstBook = new Book(name: 'Kujo', bookCategory: horrorCat).save(flush: true)