accepts_nested_attributes_for创建重复项

时间:2015-07-08 07:38:44

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems strong-parameters

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

控制器

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"}

控制台

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

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

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

为什么要创建重复项?

2 个答案:

答案 0 :(得分:5)

你的参数:

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"}

你应该发送并允许&#34; id&#34; &#34; article_collections_attributes&#34;内的属性PARAMS。例如,

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

我认为此代码可以帮助您。

答案 1 :(得分:0)

了解嵌套属性和构建 在没有article_collection的编辑操作构建对象中 例如@article.article_collection.build if @article.article_collection.blank?。如果已经有文章集合,它将不会构建新对象。