2

我正在尝试生成一个人可以在电子邮件中单击的取消订阅链接。这是我的路线的样子:

match "/unsubscribe/:email/:token" => "mailing_list_recipients#destroy", :as => :unsubscribe

当我运行时rake routes,我得到:

unsubscribe GET /unsubscribe/:email/:token(.:format) mailing_list_recipients#destroy

我什至可以这样做:

unsubscribe_url(mailing_list_recipient.email, mailing_list_recipient.token)

输出:

http://localhost:3000/unsubscribe/hello@hello.com/f99e3af9bd959c6c8f3882a6e10e354e

但是,当我尝试访问此 URL 时,出现以下错误:

No route matches [GET] "/unsubscribe/schroppl@gmail.com/6458f6a714d81a9cdd1cd1133dd65f0d"

我错过了什么?

4

3 回答 3

2

正如评论中所说,您应该简单地对电子邮件地址进行 url 编码

于 2012-12-30T22:48:01.520 回答
0

问题在于电子邮件地址:schroppl@gmail.com

您必须编写适配器。将点替换为另一个符号,例如“!” (如果您仍然需要 URL 字符串中的电子邮件):

代码可能是这样的:

# Recipient:

def email_for_url
  email.gsub(/\./,"!")
end

def self.search_by_email(url_email)
  find_by_email(url_email.gsub(/\!/,"."))
end

所以你可以使用:

unsubscribe_url(mailing_list_recipient.email_for_url, mailing_list_recipient.token)

Recipient.search_by_email(params[:email])
于 2012-12-29T03:50:06.457 回答
0

您需要对电子邮件地址进行编码,这可以通过多种方式进行。

# 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))

这将更改您的网址

http://localhost:3000/unsubscribe/hello@hello.com/f99e3af9bd959c6c8f3882a6e10e354e

http://localhost:3000/unsubscribe/hello%40hello.com/f99e3af9bd959c6c8f3882a6e10e354e
于 2012-12-30T18:36:12.113 回答