Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - URL helpers not working in mailers

I tried:

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

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

Also inside mailer:

include Rails.application.routes.url_helpers

def my_mail
  @my_route = my_helper

Also, the simple way, in mailer template:

= link_to 'asd', my_helper

But then when I try to start console I get:

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

Update

I am using the _url form of the helper, i.e. my_helper_url

like image 339
sites Avatar asked Jul 21 '13 18:07

sites


3 Answers

For Rails 5, I included the url helpers into the my mailer file:

# 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
like image 96
Constant Meiring Avatar answered Nov 09 '22 04:11

Constant Meiring


Doing this broke my other routes.

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

Doing this is not the right way, this will break application as routes are reloading and routes will not be available is those are reloading

module SimpleBackend
    extend ActiveSupport::Concern
    Rails.application.reload_routes!

Right answer is to use *_url and not *_path methods in email templates as explained below in Rails docs.

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

like image 42
omair azam Avatar answered Nov 09 '22 05:11

omair azam


I ran into the same issue but with a Concern, i was unable to use any of the url helpers in my code even using directly Rails.application.routes.url_helpers.administrator_beverages_url i was getting this error:

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

even unable to use the rails console because of this error the only way i found to solve this was to use this code in my Concern

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

The problem was Rails.application.routes.url_helpers was empty at the moment of the initialization. I don't know the performance implication of using this but for my case this is a small application and i can take the bullet.

like image 2
Dranes Avatar answered Nov 09 '22 06:11

Dranes