HABTM 和 accepts

编程入门 行业动态 更新时间:2024-10-27 08:32:14
本文介绍了HABTM 和 accepts_nested_attributes_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有两个模型,Book 和 Author,它们之间具有 has_and_belongs_to_many 关系.

Say I have two models, Book and Author with a has_and_belongs_to_many relationship between them.

我想要做的是能够在书籍表单中添加作者姓名,然后提交以将作者与书籍链接起来(如果它们已经存在),或者如果它们不存在则创建它们.

What I want to do is to be able to add author names in the book form, and on submit to either link the authors with the book if they already exist, or create them if they don't.

我也想对作者表单做同样的事情:添加书名并在提交时链接它们(如果它们存在),或者如果它们不存在则创建它们.

I also want to do the same with the author form: add book names and on submit either link them if they exist, or create them if they don't.

但是,在编辑时,我既不想编辑也不想删除嵌套对象,只想删除关联.

On edit, however, I want to neither be able to edit nor delete the nested objects, only remove the associations.

accepts_nested_attributes_for 是否适用于此,或者还有其他方法吗?

Is accepts_nested_attributes_for suitable for this, or is there another way?

我按照 Complex Forms railscasts onRails 2,但我正在为 Rails 3 寻找更优雅的解决方案.

I managed to accomplish this by following the Complex Forms railscasts on Rails 2, but I'm looking for a more elegant solution for Rails 3.

推荐答案

我不知道为什么这么多人使用 has_and_belongs_to_many,这是 Rails 1 的遗物,而不是使用 has_many ..., :through 除了它可能在很多旧的参考书和教程中.两种方法的最大区别在于,第一种使用复合键来识别它们,第二种使用一流的模型.

I'm not sure why so many people use has_and_belongs_to_many, which is a relic from Rails 1, instead of using has_many ..., :through except that it's probably in a lot of old reference books and tutorials. The big difference between the two approaches is the first uses a compound key to identify them, the second a first-class model.

如果你重新定义你的关系,你可以在中间模型级别进行管理.例如,您可以添加和删除 BookAuthor 记录,而不是 has_and_belongs_to_many 链接,这些链接众所周知难以单独调整.

If you redefine your relationship, you can manage on the intermediate model level. For instance, you can add and remove BookAuthor records instead of has_and_belongs_to_many links which are notoriously difficult to tweak on an individual basis.

您可以创建一个简单的模型:

You can create a simple model:

class BookAuthor < ActiveRecord::Base belongs_to :book belongs_to :author end

现在可以更轻松地链接您的每个其他模型:

Each of your other models is now more easily linked:

class Book < ActiveRecord::Base has_many :book_authors has_many :authors, :through => :book_authors end class Author < ActiveRecord::Base has_many :book_authors has_many :books, :through => :book_authors end

在您的嵌套表单上,直接管理 book_authors 关系,根据需要添加和删除它们.

On your nested form, manage the book_authors relationship directly, adding and removing those as required.

更多推荐

HABTM 和 accepts

本文发布于:2023-10-18 03:08:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HABTM   accepts

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!