使用accepts_nested_attribute复制has_many记录

时间:2014-04-17 00:23:48

标签: ruby-on-rails mongoid mongoid4

使用主人的Rails 4和Mongoid 4

由于某些奇怪的原因,当记录验证失败时(但有效时,我没有获得重复的子记录)然后呈现给用户的表单中有额外的记录

我有一个Pipeline,它有很多PipelineStages

将舞台名称编辑为空白(验证失败)会复制所有Pipeline.pipeline_stages

class Pipeline
  include Mongoid::Document
  has_many :pipeline_stages, dependent: :destroy
  accepts_nested_attributes_for :pipeline_stages, allow_destroy: true
end

class PipelineStage
  include Mongoid::Document
  belongs_to :pipeline
  validates :name, presence: true, length: { maximum:50 }
end

因此,当传入控制器时,使用update_attributes时看似完全有效的params不起作用

[1] pry(#<PipelinesController>)> valid_params
=> {"name"=>"ddd",
 "pipeline_stages_attributes"=>
  {"0"=>
    {"id"=>"534f170e4a616b8368960000",
     "name"=>"dddd",
     "_destroy"=>"false",
     "sort_order"=>"9999"},
   "1"=>
    {"id"=>"534f1b554a616b8368a70000",
     "name"=>"",
     "_destroy"=>"false",
     "sort_order"=>"9999"}}}
[2] pry(#<PipelinesController>)> @pipeline.pipeline_stages
=> [#<PipelineStage _id: 534f170e4a616b8368960000, created_at: 2014-04-16 23:49:34 UTC, updated_at: 2014-04-16 23:49:34 UTC, pipeline_id: BSON::ObjectId('534f170e4a616b8368950000'), name: "dddd", stage_number: nil, sort_order: 9999>, 
 #<PipelineStage _id: 534f1b554a616b8368a70000, created_at: 2014-04-17 00:07:49 UTC, updated_at: 2014-04-17 00:07:57 UTC, pipeline_id: BSON::ObjectId('534f170e4a616b8368950000'), name: "asdasdsadasd2", stage_number: nil, sort_order: 9999>]

[3] pry(#<PipelinesController>)> @pipeline.update_attributes(valid_params)
=> false

[4] pry(#<PipelinesController>)> @pipeline.pipeline_stages
=> [#<PipelineStage _id: 534f170e4a616b8368960000, created_at: 2014-04-16 23:49:34 UTC, updated_at: 2014-04-16 23:49:34 UTC, pipeline_id: BSON::ObjectId('534f170e4a616b8368950000'), name: "dddd", stage_number: nil, sort_order: 9999>, 
 #<PipelineStage _id: 534f1b554a616b8368a70000, created_at: 2014-04-17 00:07:49 UTC, updated_at: 2014-04-17 00:07:57 UTC, pipeline_id: BSON::ObjectId('534f170e4a616b8368950000'), name: "asdasdsadasd2", stage_number: nil, sort_order: 9999>, 
 #<PipelineStage _id: 534f170e4a616b8368960000, created_at: 2014-04-16 23:49:34 UTC, updated_at: 2014-04-16 23:49:34 UTC, pipeline_id: BSON::ObjectId('534f170e4a616b8368950000'), name: "dddd", stage_number: nil, sort_order: 9999>, 
 #<PipelineStage _id: 534f1b554a616b8368a70000, created_at: 2014-04-17 00:07:49 UTC, updated_at: 2014-04-17 00:07:57 UTC, pipeline_id: BSON::ObjectId('534f170e4a616b8368950000'), name: "", stage_number: nil, sort_order: 9999>]

0 个答案:

没有答案