choise
choise

Reputation: 25244

Nested forms deletion not working

i'm using nested_form for adding and deleting nested_attributes.

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

and the nested model

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

adding attachements works fine, but deleting doesent.

after clicking the delete link, the text[attachments_attributes][0][_destroy] input value changes from false to 1 so i think this is not the problem.

my update method:

  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

the output of params in my update method is

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'

i cannot find the problem, so do you have an idea whats going wrong?

thank you! please leave a comment if something is unclear!

Upvotes: 0

Views: 679

Answers (1)

cristian
cristian

Reputation: 8744

add :allow_destroy => true to accepts_nested_attributes_for :attachments

accepts_nested_attributes_for :attachments, :allow_destroy => true

More information http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Upvotes: 5

Related Questions