【发布时间】: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