Reputation: 21
I am new in grails and I need your help..
I have Author and Book domain classes:
class Author{
static hasMany = [book:Book]
String name
//....
}
class Book{
static belongsTo = [author:Author]
String title
//....
}
Domain classes have their controllers with "new" action, wich creates new object and save in db. In my browser when I enter .../myApp/author/new?name=myName&... , in my db creates author object, but when I enter .../myApp/book/new?name=title&.. it can not save book object,maybe because I have not got author object yet...
What can i do in this situation? If anyone know solution please help...
Upvotes: 1
Views: 3518
Reputation: 2003
For testing purpose you can load some data into the bootstrap:
class BootStrap {
def init = { servletContext ->
def writer = new Author(name:"Jane")
writer.save()
if(writer.hasErrors()){
println writer.errors
}
def comic = new Book(name: "superman", Author: writer)
comic.save()
if(comic.hasErrors()){
println comic.errors
}
}
def destroy = {}
}
This way your app will have an Author and a Book in it.
Also this tutorial helped me very much.
Upvotes: 0
Reputation: 10848
When defining Book belongsTo
Author, and the Author hasMany
books, the Book can not be created without the author. Often you should do things like this:
As I see you describe your problem, I think you should go slower and take a look over the basics of Grails GORM (Groovy Object Relation mapping), you can start by examples with "Getting started with Grails", or read the 3 post about GORM Gotchas. They are very comprehensible.
Upvotes: 1
Reputation: 120198
You need to pass in the id of the Author to which you want to associate the Book instance. You need to then load the Author, and associate it with the Book you want to save.
im pretty sure you can't have a controller action named 'new'. 'new' is a reserved keyword in java/groovy.
def blah = new Blah()
Upvotes: 4