所有的東西。假設你可能需要使用一個連接表。這給一展身手:
class Article < ActiveRecord::Base
has_many :article_authors
accepts_nested_attributes_for :article_authors, allow_delete: true
end
class Author < ActiveRecord::Base
has_many :article_authors
end
class ArticleAuthor < ActiveRecord::Base
belongs_to :article
belongs_to :author
accepts.nested_attributes_for :author
end
# PUT /articles/:id
params = {
id: 10,
article_authors_attributes: {
[
# Case 1, create and associate new author, since no ID is provided
{
# A new ArticleAuthor row will be created since no ID is supplied
author_attributes: {
# A new Author will be created since no ID is supplied
name: "New Author"
}
}
],
[
# Case 2, associate Author#100
{
# A new ArticleAuthor row will be created since no ID is supplied
author_attributes: {
# Referencing the existing Author#100
id: 100
}
}
],
[
# Case 3, delete ArticleAuthor#101
# Note that in this case you must provide the ID to the join table to delete
{
id: 1000,
_destroy: 1
}
]
}
}
您在使用連接表(HABTM)嗎?我認爲作者也可以有許多文章。如果你在每種情況下都包括來自你的表單的參數,這也會很有幫助。 – aceofspades 2012-12-11 18:41:38