Grails: Do addTo* and removeFrom* require a call to save?

788 views Asked by At

In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

1

There are 1 answers

0
mohsenmadi On BEST ANSWER

Neither needs a call to save() in most contexts. What you're seeing in the "some examples" link is a save to the main domain object Author, which gets persisted first, and then the other properties will make it in the database with a proper id to link back to. For example, these two snippets are equivalent as far as persistence is concerned:

def a = new Author(name: "Stephen King")
         .addToFiction(fictBook)
         .addToNonFiction(nonFictBook)
         .save()

and

def a = new Author(name: "Stephen King").save()
a.addToFiction(fictBook)
a.addToNonFiction(nonFictBook)

Sometimes, a save(flush:true) operation is needed if you're after an id for further dependent operations, otherwise it is not necessary.

To test, open two browsers, on one do your app clicking, on the other watch your .../dbconsole - persistence is prompt without the need for explicit saving.