HABTM 和 accepts_nested_attributes_for [英] HABTM and accepts_nested_attributes_for

查看:35
本文介绍了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_nested_attributes_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆