Grails: remove all associated objects
Relate开发者_运维技巧d objects of an m:n relation can be selected with a html select element in my application (could also be a list of checkboxes). If all related objects are deselected in the edit form, the objects list of related objects should be cleared. With scaffold code it works only if at least one related object remains.
Example:
class Book {
String name
static hasMany = [authors: Author]
belongsTo = Author
}
class Author {
String name
static hasMany = [books: Book]
}
def b1 = new Book(name: "B1").save()
def b2 = new Book(name: "B2").save()
def author = new Author(name: "Stephen").addToBooks(b1).addToBooks(b2).save()
// How to remove all books from the author?
Following the Grails doc I would call removeFrom*
(the opposite of addTo*
) on the domain object for all related objects. But to do this, I had to figure out, what objects are related. Is there an easier way to clear the list of related objects? Would the bidirectional association be handled correctly, if the list of related objects would simply be replaced by an empty list?
I think the issue that you might be experiencing is that when so item is selected either in the select box or via checkboxes then no data is coming back with the request to the controller. If you want to be able to remove all objects from the association you need to add an extra hidden field to the form.
For example if there is a product that has many categories add the following:
<g:hiddenField name="categories" value=""/>
apart from the usual select
.
You can write a test for the controller to make sure that the desired functionality behaves as expected.
精彩评论