将应用程序控制器方法传递给邮件程序

时间:2015-10-07 17:31:45

标签: ruby-on-rails

我想将一个方法从应用程序控制器传递给邮件程序,以便将购物车内容发送到电子邮件。

application_controller.rb中的方法:

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

邮件程序:

class CartMailer < ApplicationMailer
    default from: "from@example.com"

    def send_cart_contents
        @order = current_order
        mail(to: "to@example.com", subject: 'Order from the site')
    end
end

观点:

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

我收到错误:未定义的本地变量或方法&#39; current_order&#39;。 我究竟做错了什么?谢谢。

更新

如果我将其作为参数传递:

# 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

我也得到了NameError。

更新2

CartMailerPreview无法访问current_order,因此要测试它只是传递带参数的id。当你正常使用时一切正常。

2 个答案:

答案 0 :(得分:2)

CartMailer无法看到current_order中定义的application_controller.rb。这是一件好事。

最佳做法是让send_cart_contents方法接受订单,以便将其邮寄出去:

class CartMailer < ApplicationMailer
    default from: "from@example.com"

    def send_cart_contents(order)
        @order = order
        mail(to: "to@example.com", subject: 'Order from the site')
    end
end

通过这种方式,您可以从后台作业邮寄出购物车,并将邮件与控制器隔离开来。依赖全球current_order并不是一种好习惯。

答案 1 :(得分:0)

您应该将current_order作为参数传递给邮件程序。

相关问题