我正在使用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'
我找不到问题,所以你有什么想法会出错吗?
谢谢你! 如果不清楚,请发表评论!答案 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