Anton Khaybulaev
Anton Khaybulaev

Reputation: 89

Passing application controller method to mailer

I want to pass a method from the application controller to a mailer to send shopping cart contents to email.

Method in the application_controller.rb:

def current_order
    if session[:order_id].present?
        Order.find(session[:order_id])
    else
        Order.new
    end
end

Mailer:

class CartMailer < ApplicationMailer
    default from: "[email protected]"

    def send_cart_contents
        @order = current_order
        mail(to: "[email protected]", subject: 'Order from the site')
    end
end

And the view:

Order from the site
<% @order.order_items.each do |oi| %>
    <%= oi.product.name %>
<% end %>

I'm getting an error: undefined local variable or method 'current_order'. What am I doing wrong? Thank you.

UPDATE

If I'm passing it as a parameter:

# Preview all emails at http://localhost:3000/rails/mailers/cart_mailer
class CartMailerPreview < ActionMailer::Preview
    def cart_mailer_preview
        CartMailer.send_cart_contents(current_order)
    end
end

I'm also getting NameError.

UPDATE 2

CartMailerPreview don't have access to the current_order, so to test it just pass an id with the parameter. When you use it normally all works well.

Upvotes: 3

Views: 1093

Answers (2)

Gavin Miller
Gavin Miller

Reputation: 43815

The CartMailer is not going to have visibility to the current_order defined in application_controller.rb. This is a good thing.

Best practices is to have the send_cart_contents method accept the order so that it can mail it out:

class CartMailer < ApplicationMailer
    default from: "[email protected]"

    def send_cart_contents(order)
        @order = order
        mail(to: "[email protected]", subject: 'Order from the site')
    end
end

This way you can mail out a cart from a background job and isolates your mailers from your controllers. Relying on a global current_order is not a good practice.

Upvotes: 2

Rafal
Rafal

Reputation: 2576

You should pass current_order to the mailer as a parameter.

Upvotes: 0

Related Questions