嵌套表单删除无效

时间:2011-12-22 14:58:19

标签: ruby-on-rails ruby ruby-on-rails-3.1 nested-forms

我正在使用nested_form添加和删除nested_attributes。

class Text < ActiveRecord::Base
  attr_accessible :attachments_attributes
  has_many :attachments, :as => :attachable
  accepts_nested_attributes_for :attachments
end

和嵌套模型

class Attachment < ActiveRecord::Base
  attr_accessible :description, :file
  belongs_to :attachable, :polymorphic => true
end

添加附件工作正常,但删除了doesent。

点击删除链接后,text[attachments_attributes][0][_destroy]输入值会从false更改为1,所以我认为这不是问题。

我的更新方法:

  def update
    @text = Text.find(params[:id])
    if @text.update_attributes(params[:text])
      redirect_to @text, :notice  => "Successfully updated text."
    else
      render :action => 'edit'
    end
  end

我的更新方法中的params输出是

attachments_attributes:
  '0':
    description: asdf asdf as fs
    _destroy: '1'
    id: '2'
  '1':
    description: ''
    _destroy: '1'
    id: '3'
  '2':
    description: asdsadasd
    _destroy: '1'
    id: '4'

我找不到问题,所以你有什么想法会出错吗?

谢谢你! 如果不清楚,请发表评论!

1 个答案:

答案 0 :(得分:5)

:allow_destroy => true添加到accepts_nested_attributes_for :attachments

accepts_nested_attributes_for :attachments, :allow_destroy => true

更多信息http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html