i create two domain, Author and Book, the Author has many Book, and the Book is belongsTo Author.
class Author {
hasMany = [ books : Book ]
String name
}
class Book {
String title
Author author
}
this “savebook” function in BookController.groovy
def savebook={
def json = request.JSON
def bookInstance = new Book()
bookInstance.properties = json
bookInstance.author_id = json.author_id
bookInstance.title = json.title
if (bookInstance.validate()) {
bookInstance.save();
def rep = [ respence: "1" ] // save
render rep as JSON
}
else {
def rep = [ respence: "0" ] // not save
render rep as JSON
}
}
I have not found a solution for the line : bookInstance.author_id = json.author_id in “savebook” to create a book by an author.
My second question is how should be the structure of the JSON object to make a REST POST ?
For the first part of your question you need to look the author up by their id and assign that instance to the author variable in Book:
The structure of the JSON coming into the rest method can be any valid JSON. You could simply do
or you could get as complicated as you need.