irl_irl
irl_irl

Reputation: 3975

When I try delete a record, it creates a new one

I am trying to do a simple deletion of a record in the database.

<b> <%= button_to "Cancel your invitation", { :controller=>"invites", :method => 'destroy', :id => invite.id },
:confirm => "Are you sure you want to delete this invite?" %></b>

I specify the the controller because I am doing this action from a User view.

When I click the button, it creates a blank entry for a new record. So why would it use a create method when I specified a destroy one?

Some more into: My config/routes is as simple as can be:

resources :invites

My controller is quite basic too:

  def create
    @invite = Invite.new(params[:invite])
    if @invite.save
      redirect_to current_user
    else
      redirect_to root_path
    end
  end



  def destroy
    Invite.find(params[:id]).destroy
    redirect_to current_user
  end

Upvotes: 1

Views: 127

Answers (2)

PeterWong
PeterWong

Reputation: 16011

You misused the methods. It should be:

<b>
  <%= button_to "Cancel your invitation", invite, :confirm => "Are you sure you want to delete this invite?", :method => :delete %>
</b>

There are 2 points.

1) For resources :invites, the destroy method needs delete. Without passing :method => :delete to button_to would by default use :method => :post, which is the create method. That's why you created a new record instead of destroying it.

2) As you are using resources, you have better choice for the route instead of {:controller => "invites", :action => "destroy", :id => invite.id} (note that it was :action)

You could use invite_path(invite) or just invite just like my example above. With the :method => :delete this gives you the destroy method. (so with :post for create, :put for update)

Upvotes: 1

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

I think, you need to use delete method instead of destroy.

Upvotes: 2

Related Questions