Reputation: 335
I'm having a bit of trouble generating a link in Action Mailer that allows the resource to be deleted when clicked. Here's my code for the delete method (which works fine inside of the app):
def destroy
@registrant = Registrant.find(params[:id])
@registrant.destroy
flash[:danger] = "Your registration has successfully been cancelled."
redirect_to root_url
RegistrantMailer.cancellation_email(@registrant, @registrant.event).deliver_now
rescue
flash[:warning] = "No registration record found."
redirect_to root_url
end
Here are the routes for the application:
Prefix Verb URI Pattern Controller#Action
registrants POST /registrants(.:format) registrants#create
registrant GET /registrants/:id(.:format) registrants#show
DELETE /registrants/:id(.:format) registrants#destroy
static_pages_contact GET /static_pages/contact(.:format) static_pages#contact
static_pages_about GET /static_pages/about(.:format) static_pages#about
events GET /events(.:format) events#index
POST /events(.:format) events#create
new_event GET /events/new(.:format) events#new
edit_event GET /events/:id/edit(.:format) events#edit
event GET /events/:id(.:format) events#show
PATCH /events/:id(.:format) events#update
PUT /events/:id(.:format) events#update
DELETE /events/:id(.:format) events#destroy
root GET / static_pages#home
And here is the link from the mailer in which I want to generate the delete link:
<p>Can't make the event? Click here to cancel your registration: <%= link_to 'Destroy', @registrant, method: :delete %> </p>
Upvotes: 1
Views: 270
Reputation: 1854
The ability to issue PUT and DELETE statements from within Rails views is due to the extra work Rails does to format the links and issue requests that are universally understood by the browser. Typically, browsers will only know how to use HTTP verbs GET and POST when performing form submissions and requesting documents. Rails allows the other verbs to be used by issuing a POST request, and by supplying an HTTP header stating that the request should be interpreted as a DELETE request by the server, for example.
When you use the link_to
helper in a mailer view, the additional javascript that Rails uses to convert and issue the request isn't present, and thus the link when clicked will send a GET request with no additional information.
There are really 2 options:
1: Make the registration able to be canceled via a GET request. (This is the easiest method, but not preferred, as it would allow anyone to issue a GET request to this endpoint and delete a registration. This has happened before with web crawlers issuing GET requests in order to index pages, and inadvertently deleting many records).
2: Have the link in the mailer view direct to a GET accessible landing page in Rails. Once the user is here, the landing page will have additional instructions, and the DELETE link which will work, because the browser once again has access to the Rails javascript helpers.
Upvotes: 3