Home > Blockchain >  How to use ActiveRecord :: Nested Attributes for multiple association
How to use ActiveRecord :: Nested Attributes for multiple association

Time:11-07

I have Article, Category and CategoryArticle models

# 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

And I'd like to save the articles including the categories through the nested_attributes, for example:

# rails console
category = Category.first

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

However I get the following error:

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

If you could give me a hand on how to insert using nested_attributes I'd be very grateful

CodePudding user response:

I think you don't need accepts_nested_attributes_for here.

You can pass ids of categories when creating Article:

category = Category.first

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