Search code examples
grailsgrails-ormrelationship

How to create objects with multiple relationships in BootStrap.groovy init


I want to generate some dummy content that i can test with in BootStrap.groovy, but I'm struggling to get it to work when I have more than one relationship.

I have 3 domain classes: User, Book and Author

A user has many books. An author has many books.

I have it set up like the following:

class User {
    static hasMany = [books:Book]
}
class Author {
    static hasMany = [books:Book]
}
class Book {
    static belongsTo = [author:Author, user:User]
}

I want BootStrap.groovy to create and save a few books but i cant get it to work. Heres what I have:

def init = { servletContext ->
    def u1 = new User(login:"mrx", password:"p", name:"Mr X")
    def u2 = new User(login:"mry", password:"p", name:"Mr Y")

    def a1 = new Author(name:"Mary Shelley")
    def a2 = new Author(name:"Stephen King")

    def b1 = new Book(title:"Frankenstein")
    def b2 = new Book(title:"The Shining")
    def b3 = new Book(title:"Misery")

    a1.addToBooks(b1)
    a2.addToBooks(b2)
    a2.addToBooks(b3)

    u1.addToBooks(b1)
    u1.addToBooks(b3)
    u2.addToBooks(b2)

    a1.save()
    a2.save()

    u1.save()
    u2.save()
}

When i view Book/index (which is the scaffold and should just display a list of all books) I dont get any errors, but no books appear in the list. What am I doing wrong?


Solution

  • It seems you don't have Book instance to add. I usually just create instances with the references instead of using addTo method. E.g.

    new Book(author:a1, user:u1, title:'Test', isbn:'test').save()
    

    The relationship will be there later after the BootStrap