0

accepts_nested_attributes_for creating duplicates

Model

class Article < ActiveRecord::Base
  has_many :article_collections
  accepts_nested_attributes_for :article_collections, :allow_destroy => true, reject_if: :all_blank
end

class ArticleCollection < ActiveRecord::Base
  belongs_to :article
end

Controller

def update
  @article = Article.find_by_id(params[:id])
  @article.update_attributes(params[:article])
  redirect_to :index
end

Params

params = {"utf8"=>"✓"
   "article"=>
   {
    "data_id"=>"dfe9e32c-3e7c-4b33-96b6-53b123d70e7a", "name"=>"Mass", "description"=>"mass",
    "status"=>"active", "volume"=>"dfg", "issue"=>"srf", "iscode"=>"sdg", 
        "image"=>{"title"=>"", "caption"=>"",  "root_image_id"=>""},
    "article_collections_attributes"=>
    [
    {"name"=>"abcd", "type"=>"Special", "description"=>"content ","ordering_type"=>""}
    ]
  },
"commit"=>"Save", "id"=>"b8c8ad67-9b98-4705-8b01-8c3f00e55919"}

Console

 Article.find("b8c8ad67-9b98-4705-8b01-8c3f00e55919").article_collections.count
 => 2

Problem is whenever we are updating article it's creating multiple article_collections.

Suppose article_collections is 2 mean if we are updating article it's creating multiple article_collections = 4, it's not updating same article_collections, it's newly creating article_collections.

Why is it creating duplicates?

halfer
  • 19,824
  • 17
  • 99
  • 186
Kanna
  • 990
  • 1
  • 11
  • 30

2 Answers2

6

Your params:

params = {"utf8"=>"✓"
   "article"=>
   {
    "data_id"=>"dfe9e32c-3e7c-4b33-96b6-53b123d70e7a", "name"=>"Mass", "description"=>"mass",
    "status"=>"active", "volume"=>"dfg", "issue"=>"srf", "iscode"=>"sdg", 
        "image"=>{"title"=>"", "caption"=>"",  "root_image_id"=>""},
    "article_collections_attributes"=>
    [
    {"name"=>"abcd", "type"=>"Special", "description"=>"content ","ordering_type"=>""}
    ]
  },
"commit"=>"Save", "id"=>"b8c8ad67-9b98-4705-8b01-8c3f00e55919"}

You should send and permit the "id" attribute inside the "article_collections_attributes" params. For Example,

 "article_collections_attributes"=>
    [
    {"id"=>"2", "name"=>"abcd", "type"=>"Special", "description"=>"content ","ordering_type"=>""}
    ]

I think this code will help you.

0

Read about nested attribute and build.
In your edit action build object when it has no article_collection.
For ex.@article.article_collection.build if @article.article_collection.blank?. it will not build a new object if it has already a article collection.

Ashutosh Tiwari
  • 984
  • 6
  • 16