rails 4.1.1
我有一个OrdersController,并且在订单显示我有动作......
orders_controller.rb
def show
@order = Order.find(params[:id])
@client = Client.find(@order.client_id)
if request.post?
OrderMailer.order_send(@client, @order).deliver
flash[:notice] = 'Order details sent!'
redirect_to order_path(@order.id)
end
end
然后在我看来......
(show.haml)
= button_to "Send", @order
如果我选择" OrderMailer"在if语句之外并访问show / order页面,电子邮件会反复发送,直到我关闭开发服务器,因此我知道邮件程序部分发送/工作正常。
我只是不确定如何将按钮点击/发送电子邮件绑在一起?如果我已经有订单/显示页面的路线,我需要一条路线,但不知道如何将它绑在一起?
的routes.rb
resources :orders, :path => 'orders'
答案 0 :(得分:4)
我不确定如何使您当前的方法有效,但有几种方法可以做到这一点。这是我使用的一种方式:
设置控制器操作:
orders_controller.rb
def send_order_mail
@parameters = Model.get_parameters
OrderMailer.name_of_action(@parameters).deliver
# redirect code here
end
设置路线:
get send_order_mail, to: 'orders_controller#send_order_mail', as: :send_order_mail
然后建立你的链接。
link_to 'Send mail', send_order_mail_path, class: "big-button"
答案 1 :(得分:2)
好的,在@steel的帮助下,这里是代码。
routes.rb(将开头更改为符号)
get :send_order_mail, to: 'orders#send_order_mail', as: :send_order_mail
orders_controller.rb
def send_order_mail
@order = Order.find(params[:id])
@client = Customer.find(@order.client_id)
OrderMailer.order_send(@order, @client).deliver
flash[:notice] = "Order has been sent."
redirect_to order_path(@order.id)
end
orders / show.html.erb上有链接。
<%= link_to "Send Order by email", :controller => "orders", :action => "send_order_mail", :id => @order.id %>
寄件人/ order_mailer.rb
class OrderMailer < ActionMailer::Base
add_template_helper(OrdersHelper)
default from: "mail@example.com"
def order_send(order, client)
@order = order
@client = client
mail(to: "#{@client.email}", subject: "Your subject")
end
end