Question

I have a problem with the destroy action. It works in the index.html.erb very fine. But I can't get it work in the edit.html.erb It routes to the show even without asking for a permission.

Many solutions here say it has something to do with jQuery. Well as you can see, I tried all I could find.

<%= stylesheet_link_tag    "application" %>
    <!--Delete Problem in Edit-->
    <%#= javascript_include_tag :all %>
    <%#= javascript_include_tag :application %>
    <%#= javascript_include_tag :default %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>

Is there a solution that works for my situation?

This is my delete button in edit:

<%= content_tag(:a, :href => contact_path(@contact), :class => "btn btn-warning pull-right", :style => "margin:0; margin-right:15px;", confirm: 'Are you sure?', method: :delete) do %>
<%= t "list.button_delete" %>
        <%#= link_to I18n.t(".list.delete"), contact, confirm: 'Are you sure?', method: :delete %>
        <%#= link_to 'delete', contact_path(@contact), :method => :delete %>
<% end %>

I tried many things, as well.

The following is the action:

def destroy
    #@contact = Contact.find(params[:id])
    @contact = current_user.contacts.find(params[:id])
    @contact.destroy
    redirect_to contacts_url,
                            alert: 'Successfully deleted the contact'
end
Was it helpful?

Solution

Replace

<%= content_tag(:a, :href => contact_path(@contact), :class => "btn btn-warning pull-right", :style => "margin:0; margin-right:15px;", confirm: 'Are you sure?', method: :delete) do %>

with

<%= content_tag(:a, :href => contact_path(@contact), :class => "btn btn-warning pull-right", :style => "margin:0; margin-right:15px;", data: {confirm: 'Are you sure?'}, data: {method: :delete}) do %>

It should be data: {confirm: 'Are you sure?'} instead of confirm: 'Are you sure?' and also data: {method: :delete} instead of method: :delete .

where, link_to method interpolates confirm: 'Are you sure?' as data-confirm="Are you sure?" and method: :delete as data-method="delete".

BUT content_tag method interpolates confirm: 'Are you sure?' as confirm="Are you sure?" and method: :delete as method="delete" so your javascript call is not getting invoked.

OTHER TIPS

In your destroy action replace:

@contact = current_user.contacts.find(params[:id])

with:

@contact = @current_user.contacts.find(params[:id])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top