Reputation: 1736
I have a Subscriber model which is created when somebody subscribes. And by that time, I send the subscriber(person) an email that informs about the subscription. In that mail I'd like to include a link to delete the subscription but I could not get it in the destroy action, instead it goes to the show action.
my link_to code in mailer template is this
= link_to 'this link', controller: "subscribers", action: "destroy", id: @subscription, token: @subscription.token, only_path: false
I'd like to to call the destroy action to be able to remove the subscription.
I tried googling but haven't found an example of a delete action called through a mailer
by the way, I use mailcatcher to test the mailer
UPDATE
here is my destroy action code as requested
def destroy
#@subscriber being fetch through before filter
@subscriber.destroy
flash[:success] = "Subscription was deleted."
redirect_to subscribers_path
end
Id like to add that there are administrators that could also delete subscribers which already works...
Upvotes: 1
Views: 805
Reputation: 1736
Sorry It seems that the question is somehow a duplicate... can't generate delete link in rails mailing view
The reason is not working, i think, is because the :method => :delete is handled with javascript, and since the link is clicked from the email, javascript is not triggered. The way I would have try to solve this is by passing a parameter to the url like "delete=true" and handle it with that in the controller.
So what I did is created a new route
resources subscribers do
member do
get :unsubscribe
end
end
in the mailer view i used
link_to 'this link', controller: "subscribers", action: "unsubscribe", id: @subscription, token: @subscription.token, only_path: false
I'll just use paranoid to mark the subscription deleted. That would be the difference between the destroy and unsubscribe action..
UPDATE
Also another pattern which is widely used, is that the link from the email redirects to a form (with put, post or delete request) to your application. And it is what i finally did.
Thank you!
Upvotes: 1
Reputation: 17949
Something like this:
= link unsubscribe_subscribtions_url(@subscription, token: @subscription.token)
app/controllers/subscriptions_controller.rb
class SubscriptionsController
. . .
def unsubscribe
unless params[:token]
@subscription = Subscription.find(params[:token])
@subscription.destroy if @subscription.token == params[:token]
redirect_to subscriptions_path, flash: { notice: 'Your email was unsubscribed' }
end
end
end
config/routes.rb
. . .
resources :subsriptions do
collection do
get :unsubscribe # http://example.com/subscriptions/unsubscribe?token=xxxxxx
end
end
. . .
Something like that
Upvotes: 1