Tarscher
Tarscher

Reputation: 1933

creating a form to delete a resource

I have a subscriber resource (mailinglist) and want to make a unsubscribe form. I created a remove view with a form

<%= form_for(Subscriber.new, :action => :delete) do  %>   
 email: <%= text_field_tag :mail %>   
 <%= submit_tag "Sign out" %> 
<% end %>

I try to call the delete method of the controller but instead the edit action gets called.

Upvotes: 0

Views: 3342

Answers (2)

DanneManne
DanneManne

Reputation: 21180

The problem is that the RESTful routes to the destroy action needs an :id of the resource to be deleted and since you use Subscriber.new as a source for creating the form, it cannot create an appropriate url to post to.

You can go around this by using routes like this:

<% form_for(:subscriber, :url => subscriber_path("email"), :html => {:method => :delete}) do  %>
  email: <%= text_field_tag :mail %>
  <%= submit_tag "Sign out" %>
<% end %>

Note that you have to edit subscriber_path to your own routing but by using "email" as an identifier you make sure that no faulthy :id is being passed to the controller and you can use the email to find the correct model to destroy as I think was what you wanted to do.

Upvotes: 8

Shreyas
Shreyas

Reputation: 8757

<%= form_for @subscriber, :method => :delete do  %>   
  email: <%= text_field_tag :mail %>   
  <%= submit_tag "Sign out" %> 
<% end %>

This should do the trick.

Upvotes: 2

Related Questions