我有文章、類別和類別文章模型
# 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 進行插入,我將不勝感激
uj5u.com熱心網友回復:
我認為你不需要accepts_nested_attributes_for這里。
您可以在創建文章時傳遞類別的 id:
category = Category.first
article = Article.create(name: "country", category_ids: [category.id])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351140.html
