【问题标题】:How to use ActiveRecord :: Nested Attributes for multiple association如何使用 ActiveRecord :: 嵌套属性进行多重关联
【发布时间】:2021-12-19 23:21:19
【问题描述】:

我有 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 插入,我将不胜感激

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rubygems


    【解决方案1】:

    我认为你在这里不需要accepts_nested_attributes_for

    创建文章时可以传递分类的id:

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

    【讨论】:

    • 非常感谢您的解决方案和时间:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多