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

jua*_*tas 12 ruby-on-rails actionmailer urlhelper

我试过了:

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

  def my_mail
    @my_route = routes.my_helper
    ... code omitted 
  end
Run Code Online (Sandbox Code Playgroud)

邮件内部也是:

include Rails.application.routes.url_helpers

def my_mail
  @my_route = my_helper
Run Code Online (Sandbox Code Playgroud)

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

= link_to 'asd', my_helper
Run Code Online (Sandbox Code Playgroud)

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

undefined method `my_helper' for #<Module:0x007f9252e39b80> (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

更新

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

Con*_*ing 11

对于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
Run Code Online (Sandbox Code Playgroud)


oma*_*zam 5

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

# mailers/invoice_mailer.rb
include Rails.application.routes.url_helpers
Run Code Online (Sandbox Code Playgroud)

这样做不是正确的方法,这会破坏应用程序,因为正在重新加载路线,并且正在重新加载的路线将不可用

module SimpleBackend
    extend ActiveSupport::Concern
    Rails.application.reload_routes!
Run Code Online (Sandbox Code Playgroud)

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

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


obe*_*nda 1

在邮件程序中添加

helper :my
Run Code Online (Sandbox Code Playgroud)

或您需要的帮手

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

享受