How to use absolute urls and helpers from mailers with Rails Or Spree

How to use absolute urls and helpers from mailers with Rails Or Spree

First thing first: Don’t forget to setup the environments in my case for example:
config/environments/development.rb

# mailer defaults
config.action_mailer.default_url_options = { :host => "localhost:3000" }

config/environments/production.rb

config.action_mailer.default_url_options = { :host => 'elh.mx' }

And now let’s add the helpers

If you are just using the Rails you can do something like:

module MailersHelper
  def host_url_for(url_path)
    root_url.chop + url_path
  end
end


and require the helper in your mailer:

class Mailer < ActionMailer::Base
  default from: "no-reply@lhola.com"

  helper :mailers

  def my_method
    @myId = 'id'
  end
end

mailers/my_method.html.erb:

<%- edit_path = your_route_path(@myId) %>
<%= link_to 'Anchor text', host_url_for(edit_path) %>

If you’re using Spree you can do it like so:

module MailersHelper
  def spree_host_url_for(url_path)
    spree.root_url.chop + url_path
  end
end

and require the helper in your mailer:

class Mailer < ActionMailer::Base
  default from: "no-reply@lhola.com"

  helper :mailers

  def my_method
    @myOrderNumber = 'R23234234'
  end
end

mailers/my_method.html.erb:

<%- edit_order_path = spree.edit_admin_order_path(@myOrderNumber) %>
<%= link_to "#{@myOrderNumber}",
            spree_host_url_for(edit_order_path) %>
No Comments

Post A Comment