Grails:删除所有关联的对象

发布于 2024-10-04 13:03:53 字数 692 浏览 1 评论 0原文

m:n 关系的相关对象可以使用我的应用程序中的 html select 元素进行选择(也可以是复选框列表)。如果在编辑表单中取消选择所有相关对象,则应清除相关对象的对象列表。对于脚手架代码,仅当至少保留一个相关对象时,它才起作用。

示例:

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?

按照 Grails 文档,我将在所有相关对象的域对象上调用 removeFrom* (与 addTo* 相反)。但要做到这一点,我必须弄清楚哪些对象是相关的。有没有更简单的方法来清除相关对象的列表?如果相关对象的列表只是被空列表替换,双向关联是否可以正确处理?

Related 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏九 2024-10-11 13:03:53

我认为您可能遇到的问题是,当在选择框中或通过复选框选择该项目时,没有数据随控制器的请求返回。如果您希望能够从关联中删除所有对象,您需要向表单添加额外的隐藏字段。

例如,如果有一个产品有很多类别,请添加以下内容:

<g:hiddenField name="categories" value=""/>

除了通常的 select

您可以为控制器编写测试,以确保所需的功能按预期运行。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文