【问题标题】:accepts_nested_attributes_for creating duplicates接受嵌套属性用于创建重复项
【发布时间】:2015-07-08 07:38:44
【问题描述】:

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 = {"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。

为什么要创建重复项?

【问题讨论】:

  • 为什么在使用 Rails 4 时有params[:article]
  • 请用表单发表您的看法。

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


【解决方案1】:

你的参数:

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_collections_attributes”参数中的“id”属性。例如,

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

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

【讨论】:

  • 是的@Thirumal Sakthivel 我们错过了 id
  • 这是 100%。超级容易错过。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多