accepts_nested_attributes_for创建重复项

Kan*_*nna 0 ruby rubygems ruby-on-rails strong-parameters ruby-on-rails-4

accepts_nested_attributes_for创建重复项

模型

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
Run Code Online (Sandbox Code Playgroud)

调节器

def update
  @article = Article.find_by_id(params[:id])
  @article.update_attributes(params[:article])
  redirect_to :index
end
Run Code Online (Sandbox Code Playgroud)

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"}
Run Code Online (Sandbox Code Playgroud)

安慰

 Article.find("b8c8ad67-9b98-4705-8b01-8c3f00e55919").article_collections.count
 => 2
Run Code Online (Sandbox Code Playgroud)

问题是,每当我们更新文章时,它都会创建多个article_collections.

假设article_collections是2意思是如果我们正在更新文章它创建多个article_collections = 4,它没有更新相同的article_collections,它是新创建的article_collections.

为什么要创建重复项?

Thi*_*vel 6

你的参数:

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"}
Run Code Online (Sandbox Code Playgroud)

您应该发送并允许"article_collections_attributes"参数内的"id"属性.例如,

 "article_collections_attributes"=>
    [
    {"id"=>"2", "name"=>"abcd", "type"=>"Special", "description"=>"content ","ordering_type"=>""}
    ]
Run Code Online (Sandbox Code Playgroud)

我认为这段代码会对你有所帮助.