Ruby on rails 将应用程序控制器方法传递给mailer
我想将一个方法从应用程序控制器传递到邮件程序,以将购物车内容发送到电子邮件 应用程序_controller.rb中的方法:Ruby on rails 将应用程序控制器方法传递给mailer,ruby-on-rails,Ruby On Rails,我想将一个方法从应用程序控制器传递到邮件程序,以将购物车内容发送到电子邮件 应用程序_controller.rb中的方法: def current_order if session[:order_id].present? Order.find(session[:order_id]) else Order.new end end 梅勒: class CartMailer < ApplicationMailer default
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
class-CartMailer
以及以下观点:
Order from the site
<% @order.order_items.each do |oi| %>
<%= oi.product.name %>
<% end %>
从站点订购
我得到一个错误:未定义的局部变量或方法“current_order”。
我做错了什么?多谢各位
更新
如果我将其作为参数传递:
# 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
#在http://localhost:3000/rails/mailers/cart_mailer
类CartMailerPreview
我也有名字错误
更新2
CartMailerPreview没有访问当前订单的权限,因此要测试它,只需传递一个带有参数的id。当您正常使用它时,一切都很好。您应该将当前订单作为参数传递给邮件程序。CartMailer将无法查看
应用程序控制器.rb
中定义的当前订单。这是一件好事
最佳做法是让send\u cart\u 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
class-CartMailer
通过这种方式,您可以从后台作业发送购物车,并将您的邮件发送者与控制器隔离。依赖全局当前\u订单不是一个好做法。从哪里调用发送购物车\u内容?现在我从购物车\u邮箱\u预览.rb(ActionMailer::preview)调用它无论如何,如果订单存储在会话中,我不知道如何访问它?@AntonKhaybulaev在使用CartMailerPreview
时,您需要执行:CartMailer.send\u cart\u contents(order.find())
谢谢,我刚刚解决了。当我正常使用它时(不是从CartMailerPreview),它就像一个符咒。好吧,我知道了,但如果我把它作为参数传递,我也会得到NameError。我会更新最初的帖子。