问题 Rails - 不在邮件程序中工作的URL帮助程序


我试过了:

class MyMailer
  def routes
    Rails.application.routes.url_helpers
  end

  def my_mail
    @my_route = routes.my_helper
    ... code omitted 
  end

邮件内部也是:

include Rails.application.routes.url_helpers

def my_mail
  @my_route = my_helper

另外,简单的方法,在邮件模板中:

= link_to 'asd', my_helper

但是当我尝试启动控制台时,我得到:

undefined method `my_helper' for #<Module:0x007f9252e39b80> (NoMethodError)

更新

我正在使用 _url 帮助者的形式,即 my_helper_url


5643
2017-07-21 18:03


起源

请接受一个帮助您的答案。 :) - Constant Meiring


答案:


对于Rails 5,我将url助手包含在我的邮件文件中:

# mailers/invoice_mailer.rb
include Rails.application.routes.url_helpers

class InvoiceMailer < ApplicationMailer
    def send_mail(invoice)
        @invoice = invoice
        mail(to: @invoice.client.email, subject: "Invoice Test")
    end
end

9
2018-01-30 17:44



此解决方案可能会导致问题。具体来说它可以打破 link_to 在heroku上部署时的其他模板。我想这是rails中的一个bug,但可能需要一个不同的解决方法,就像我一样。参考: stackoverflow.com/questions/34573087/... - gdxn96


我遇到了同样的问题,但有一个关注,我甚至无法使用我的代码中的任何网址助手,甚至直接使用 Rails.application.routes.url_helpers.administrator_beverages_url 我收到了这个错误:

undefined method `administrator_beverages_url' for #<Module:0x00000002167158> (NoMethodError)

甚至无法使用rails控制台,因为这个错误,我发现解决这个问题的唯一方法是在我的关注中使用此代码

module SimpleBackend
    extend ActiveSupport::Concern
    Rails.application.reload_routes! #this did the trick
.....

问题是Rails.application.routes.url_helpers在初始化时是空的。我不知道使用它的性能影响,但对于我的情况,这是一个小应用程序,我可以采取子弹。


2
2017-11-22 15:56





在邮件中添加

helper :my

或者你需要的助手

它将加载app / helpers / my_helper.rb并包含MyHelper

请享用


0
2017-07-21 18:09



谢谢,但我正在尝试使用Rails路由助手。我想你在谈论助手 app/helpers - juanpastas


铁路路线助手在 Rails.application.routes.url_helpers。你应该只能放 include Rails.application.routes.url_helpers 虽然我没有对此进行测试,但是在班级的顶层


0
2017-07-21 22:15



我试过这个,这很奇怪。更奇怪的是,如果我使用url helper,环境不会加载,但我可以:1。注释行,2。启动服务器,例如,3。取消注释第4行。它可以工作。但这对真实环境不起作用。作为一个时间解决方案,我使用的是静态网址:www.blahblahblah.com / ... - juanpastas
这对我不起作用。 - Eric Walker


请查看此博客,其中介绍了如何以正确的方式使用Rails.application.routes.url_helpers。

http://hawkins.io/2012/03/generating_urls_whenever_and_wherever_you_want/


0
2017-11-24 11:09





我在处理一个似乎在我的邮件程序中无法使用的新添加的路线时遇到了这个问题。我的问题是我需要重新启动所有工人,所以他们会选择新添加的路线。离开这个 脚注 在这里万一有人遇到同样的问题,如果你不知道这种情况发生,解决起来可能会很棘手。


0
2018-01-12 15:45





这样做打破了我的其他路线。

邮寄/ invoice_mailer.rb

包括Rails.application.routes.url_helpers

这样做不是正确的方法,这将破坏应用程序,因为路由正在重新加载,并且路由将无法重新加载 模块SimpleBackend     扩展ActiveSupport ::关注     Rails.application.reload_routes!

正确答案是在电子邮件模板中使用* _url而不是* _path方法,如下面Rails文档中所述。

https://guides.rubyonrails.org/action_mailer_basics.html#generating-urls-in-action-mailer-views


0
2017-10-01 00:13