Using helper methods in email templates


#1

hi

I’m creating an template for an html email. My own helper method
‘format_price’ is not accepted, but it works in some other templates.

application_helper.rb:

Methods added to this helper will be available to all templates in

the application.
module ApplicationHelper
def format_price(amount)
euro, cents = amount.divmod(100)
sprintf(“EUR %d,%02d” , euro, cents)
end
end

order_mailer.rb:

class OrderMailer < ActionMailer::Base
def confirmation(order)
@subject = ‘’
@body = { :order => order }
@recipients = order.customer.email
@from = “removed_email_address@domain.invalid”
@sent_on = Time.now
@headers = {}
end
end

private method in the controller:

def confirm_order(order)
email = OrderMailer.create_confirmation(order) # line 185
email.set_content_type(“text/html”)
render(:text => “

” + email.encoded + “
” )
end

the error message:

NoMethodError in Cart_and_orders#new_order
Showing app/views/order_mailer/confirmation.rhtml where line #23
raised:

undefined method `format_price’ for #ActionView::Base:0x47ca250

Extracted source (around line #23):

20:

<%= order_item.times %>×
21: <%= h(order_item.product.title) %>
22:
23: <%=
format_price(order_item.product.price) %>
24: <%=
format_price(order_item.product.price * order_item.times) %>
25:
26: <% end %>

RAILS_ROOT: ./script/…/config/…

Application Trace | Framework Trace | Full Trace
#{RAILS_ROOT}/app/views/order_mailer/confirmation.rhtml:23:in
_run_rhtml_47app47views47order_mailer47confirmation46rhtml' #{RAILS_ROOT}/app/views/order_mailer/confirmation.rhtml:18:in_run_rhtml_47app47views47order_mailer47confirmation46rhtml’
#{RAILS_ROOT}/app/controllers/cart_and_orders_controller.rb:185:in
confirm_order' #{RAILS_ROOT}/app/controllers/cart_and_orders_controller.rb:155:innew_order’
#{RAILS_ROOT}/app/controllers/cart_and_orders_controller.rb:151:in
`new_order’


#2

Add a reference to your helper in your OrderMailer ActionMailer class,
like this:

helper :application

That should solve your problem (at least this is what I do to fix it).

Regards,

Dave
http://www.stevensonsoftware.com - affordable VPS Hosting
http://www.gotossh.com - web based SSH