Search code examples
ruby-on-railsnested-attributes

Rails Nested Attributes destroy some children attributes and update some others


I have Parent and Child models.

Parent

# Attributes: name, age
has_many :children, class_name: 'Child'
accepts_nested_attributes_for :children

Child

# Attributes :name, :age, :klass
belongs_to :parent

In the ParentsController

def update()
  @parent.update(parent_params)
end

def parent_params
  params.require(:parent).permit(:name, :age, :children_attributes => [:id, :name, :age, :klass])
end

Eg: Parent with id 1 has 3 children with ids [1,2,3]. I have been able to add new children and update existing children at a time.

But I want to delete the child with id 1 and update children with id 2. Can Someone help me in this?


Solution

  • I got the solution after some more research.

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

    add allow destroy option in Parent model

    accept_nested_attributes_for :children, allow_destroy: true
    

    Now, we can mark the children hash that we want to delete by adding _destroy: 1 or any true value to the hash.

    Eg.

    Parent.find(1).update_attributes(name: "New Parent Name", children_attributes: [{id: 1, _delete: 1}, {id: 2, name: 'New Name', age: 12, klass: 5}])
    

    This will update the parent and also delete child with id 1, update child with id 2 and child with id 3 will remain untouched.