Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accepts_nested_attributes_for rails 4 is not deleting

I have been reading and researching for about 3 days now. This is my last resort.

land.rb:

has_many :uploads , :dependent => :destroy
accepts_nested_attributes_for :uploads, :allow_destroy => true,:reject_if => :all_blank

upload.rb

belongs_to :land

_land_form_partial.html.erb

<%= form_for land , :html => {:multipart => true} do |f| %>

    <%= f.fields_for :uploads do |builder| %>
        <div class="land_fields">
            <%= builder.label :filename, "Image" %>
            <%= builder.text_field :filename %>   <br/>
            Delete: <%= builder.check_box :_destroy %>
        </div>
    <% end %>
 #... buttons and other fields
<% end %>

lands_controller.rb

def update
    if @land.update_attributes(land_params)
      flash[:success] = "Land updated"
      redirect_to lands_path
    else
      flash[:alert] = @land.errors.full_messages.first
      redirect_to edit_land_path
    end
  end

 def land_params  
    params.require(:land).permit( uploads_attributes: [ :id, :filename ]  )
  end

When I add something to the text field and update it, all updates properly. If I click on the check-box it won't remove the field.

Can someone please shed a light on this?

Also I tried awesome_nested_fields still everything works except for removing the actual record.

thank you in advance.

EDIT: Solution: (I like to put the solution in the question in case someone wants to view it on mobile as I hate when I can't see the solution straight away)

Thanks to @nTraum

def land_params  
    params.require(:land).permit( uploads_attributes: [ :id, :filename, :_destroy ]  )
end

And all will be dandy :)

like image 770
Mr H Avatar asked Nov 21 '13 10:11

Mr H


2 Answers

You need to allow the :_destroy parameter for your nested model as well, as this gets used when you check the 'Delete' checkbox in the form. It's Rails' way of flagging model instances that have to be destroyed.

def land_params  
  params.require(:land).permit(uploads_attributes: [:id, :filename, :_destroy])
end
like image 185
nTraum Avatar answered Nov 09 '22 19:11

nTraum


The OP didn't have the same problem as me, but for anyone coming across this question, for me, it was the absence of allow_destroy: true as an argument on the accepts_nested_attributes call in the model.

like image 23
IanBussieres Avatar answered Nov 09 '22 17:11

IanBussieres