Reputation: 10264
I'm trying to generate an unsubscribe link that a person can click on in an email. Here's what my route looks like:
match "/unsubscribe/:email/:token" => "mailing_list_recipients#destroy", :as => :unsubscribe
When I run rake routes
, I get:
unsubscribe GET /unsubscribe/:email/:token(.:format) mailing_list_recipients#destroy
I can even do:
unsubscribe_url(mailing_list_recipient.email, mailing_list_recipient.token)
which outputs:
http://localhost:3000/unsubscribe/[email protected]/f99e3af9bd959c6c8f3882a6e10e354e
However, when I try to visit this URL, I get the following error:
No route matches [GET] "/unsubscribe/[email protected]/6458f6a714d81a9cdd1cd1133dd65f0d"
What am I missing?
Upvotes: 2
Views: 118
Reputation: 115541
As said in comment, you should simply url encode the email address
Upvotes: 2
Reputation: 3766
You need to encode the email address, which you can do in any number of ways.
# ERB in your view
<%=u unsubscribe_url(mailing_list_recipient.email, mailing_list_recipient.token) %>
# Using Rack::Utils
Rack::Utils.escape(unsubscribe_url(mailing_list_recipient.email, mailing_list_recipient.token))
# Using URI::escape
URI::escape(unsubscribe_url(mailing_list_recipient.email, mailing_list_recipient.token))
This will change your URL from
http://localhost:3000/unsubscribe/[email protected]/f99e3af9bd959c6c8f3882a6e10e354e
to
http://localhost:3000/unsubscribe/hello%40hello.com/f99e3af9bd959c6c8f3882a6e10e354e
Upvotes: 0
Reputation: 4496
The problem is in the point of the email address: [email protected].
You have to write adapters. Replace point with another symbol, like "!" (if you still want email in URL string):
Code could be something like that:
# Recipient:
def email_for_url
email.gsub(/\./,"!")
end
def self.search_by_email(url_email)
find_by_email(url_email.gsub(/\!/,"."))
end
So you can use:
unsubscribe_url(mailing_list_recipient.email_for_url, mailing_list_recipient.token)
Recipient.search_by_email(params[:email])
Upvotes: 0