【问题标题】:How can I use Devise's `confirmation_url` outside of a mailer?如何在邮件之外使用设计“确认 url”?
【发布时间】:2015-02-17 18:31:33
【问题描述】:

我在 Rails 项目中使用 Devise。我想将确认网址传递给第三方。该 url 由以下 Devise Mailer 视图中的表达式 confirmation_url(@resource, confirmation_token: @token) 生成:

https://github.com/plataformatec/devise/blob/master/app/views/devise/mailer/confirmation_instructions.html.erb

我已经搜索了 Devise 的整个源代码,试图找出 confirmation_url 定义的是谁或在哪里,但我找不到任何东西;它只出现在视图上,所以它必须是由某些东西动态生成的。

在常规 Rails 应用程序中,我可以使用 Rails.application.routes.url_helpers 生成 url(例如 Rails.application.routes.url_helpers.user_path(@user))。

我可以用什么类似的东西在邮件视图之外调用confirmation_url

【问题讨论】:

  • 我不确定,但我认为这会有所帮助:stackoverflow.com/questions/3986445/… 因为您将在数据库中拥有确认令牌,然后您可以轻松创建 url。希望这会有所帮助
  • 它正在生成here,它也可以在控制器中使用。
  • 感谢您的 cmets。不幸的是,我也需要在控制器之外使用它:(。至少我知道它现在是在哪里生成的。

标签: ruby-on-rails ruby devise


【解决方案1】:

好吧,在与这个问题斗争了一段时间后,我决定阅读该文件顶部附近的解释:

https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/url_helpers.rb

事实证明,Devise 默认生成的(至少在我的应用程序中)是路由。 confirmation_url 是一个 helper,但您仍然可以看到 Devise 生成的 routes

rake routes | grep confirm

由于我使用的是名为 Account 而不是 User 的模型,所以我得到了这个:

account_confirmation     POST /accounts/confirmation(.:format)  accounts/confirmations#create
new_account_confirmation GET  /accounts/confirmation/new(.:format) accounts/confirmations#new
                         GET  /accounts/confirmation(.:format)                         accounts/confirmations#show
confirm_account        PATCH  /accounts/confirmation(.:format)                         accounts/confirmations#update

通过查看生成的电子邮件,我确认电子邮件看起来像这样:

http://myserver.com/accounts/confirm?confirmation_token=xxxx

这是上面清单中的第三个路由 - 第二个 GET。由于我不知道的原因,rails 不会打印类似显示的路线的名称,但您可以从顶部的 POST 中推断出来;该路线被命名为account_confirmation。所以现在我可以使用 rails url helper 自己生成 url:

Rails.application
     .routes.url_helpers
     .account_confirmation_url(confirmation_token: account.confirmation_token)

这将返回一个类似上面的网址。请记住将account 替换为user,或者您使用Devise 进行身份验证的任何其他内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多