我试过了:
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
对于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
我遇到了同样的问题,但有一个关注,我甚至无法使用我的代码中的任何网址助手,甚至直接使用 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在初始化时是空的。我不知道使用它的性能影响,但对于我的情况,这是一个小应用程序,我可以采取子弹。
在邮件中添加
helper :my
或者你需要的助手
它将加载app / helpers / my_helper.rb并包含MyHelper
请享用
铁路路线助手在 Rails.application.routes.url_helpers
。你应该只能放
include Rails.application.routes.url_helpers
虽然我没有对此进行测试,但是在班级的顶层
我在处理一个似乎在我的邮件程序中无法使用的新添加的路线时遇到了这个问题。我的问题是我需要重新启动所有工人,所以他们会选择新添加的路线。离开这个 脚注 在这里万一有人遇到同样的问题,如果你不知道这种情况发生,解决起来可能会很棘手。
这样做打破了我的其他路线。
邮寄/ 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