如何使用 ActiveRecord::Nested Attributes 进行多重关联

How to use ActiveRecord :: Nested Attributes for multiple association

我有 Article、Category 和 CategoryArticle 模型

# models/article.rb
Article < ApplicationRecord
  has_many :category_articles
  has_many :categories, through: :category_articles

  accepts_nested_attributes_for :categories
end

# models/category.rb
Category < ApplicationRecord
  has_many :category_articles
  has_many :articles, through: :category_articles
end

# models/category.rb
CategoryArticle < ApplicationRecord
  belongs_to :category
  belongs_to :article
end

并且我想通过nested_attributes保存包含分类的文章,例如:

# rails console
category = Category.first

article = Article.create(name: "country", categories_attributes: { id: category.id })

但是我收到以下错误:

/nested_attributes.rb:594:in `raise_nested_attributes_record_not_found!': Couldn't 
 find Category with ID=1 for Article with ID= (ActiveRecord::RecordNotFound)

如果你能教我如何使用 nested_attributes 插入,我将不胜感激

我想你不需要accepts_nested_attributes_for这里。

您可以在创建文章时传递分类ID:

category = Category.first

article = Article.create(name: "country", category_ids: [category.id])