邮件程序路由 link

Route for mailer link

账户激活

我使用的账号激活路由和邮件link如下:

# Route:
resources :account_activations, only: [:edit]

# Link in mailer:    
<%= edit_account_activation_url(@user.activation_token, email: @user.email) %>

link 生成一个 link 例如 http://www.example.com/account_activations/q5lt38hQDc_959PVoo6b7A/edit?email=foo%40example.com。控制器方法使用电子邮件地址查找用户。

更新电子邮件地址的类似内容

现在,如果用户更改了其电子邮件地址,我想做一些类似的确认 link。我已经设置了各种控制器和模型方法,但我认为邮件程序和路由中的 link 出错了。我有:

# Route (should be the same as edit route above, but now for update_email):
get 'account_activations/update_email/:email' => 'account_activations#update_email', as: 'update_email'

# Link in mailer:
<%= update_email_url(@user.activation_token, email: @user.email) %>

问题:

link 应根据其电子邮件地址识别用户(就像激活帐户一样)并生成 link,例如:http://www.example.com/account_activations/q5lt38hQDc_959PVoo6b7A/update_email?email=foo%40example.com。相反,它现在生成一个 link,例如 http://www.example.com/account_activations/update_email/foo@example.com

我认为这是错误的路线,但我不确定如何 'mimick' 我拥有的用于帐户激活的编辑路线。

尝试的替代路线:

更新:

如果我使用路线:

get 'account_activations/:id/update_email' => 'account_activations#update_email', as: 'update_email'

根据rake routes两者似乎相似:

edit_account_activation GET    /account_activations/:id/edit(.:format)         account_activations#edit
           update_email GET    /account_activations/:id/update_email(.:format) account_activations#update_email

对我来说,我的情况似乎与 "account activations" 相同。然而,虽然这对 "account activations" 有效,但为了更新电子邮件,当邮寄者应该发送 link 时,它会产生错误:

No route matches {:action=>"update_email", :controller=>"account_activations", :email=>"example@example.com", :id=>nil} missing required keys: [:id]

get 'account_activations/update_email/:id' => 'account_activations#update_email', as: 'update_email'. Here I get an error saying missing required keys: [:id].

您收到此错误是因为在您的 config/routes.rb 文件中,您说的是 get 'account_activations/update_email/:id,因此有必要发送 id 每当你触发这条路线时。而你当你不发送 id 时,你会得到错误。

get 'account_activations/update_email' => 'account_activations#update_email', as: 'update_email'. Here I get a link such http://www.example.com/account_activations/update_email?email=foo%40example.com. So again the token is missing from the link.

如果你真的想要随请求一起发送令牌,你必须像get 'account_activations/update_email/:token'一样在get 'account_activations/update_email'中提到它,这样 - 它将附加 URL.

resources :account_activations, only: :update. And changed the link to <%= account_activation_url(@user.activation_token, email: @user.email) %> (and of course change the method name in the controller). This produces the error message:

No route matches {:action=>"update", :controller=>"account_activations", :email=>"example@example.com", :id=>nil} missing required keys: [:id].

好吧,这就是我在评论中向您解释的内容。 update 方法确实需要您尝试更新的模型的 id。没有 id,它将无法工作。

所以,最后 - 我建议的解决方案是:使用 get 路由创建一个自定义方法,然后发送令牌和 id 附带 URL .