Reputation: 575
rails 4.1.1
I have an OrdersController and on the orders show action I have...
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
Then on the view I have...
(show.haml)
= button_to "Send", @order
If I take the "OrderMailer" out of the if statement and visit the show/ order page, the email gets sent repeatedly until I close the dev server so I know the mailer part sends/ works ok.
I am just unsure how to tie the button click/send email together? I need a route but not sure how to tie it together if I already have a route for the orders/show page?
routes.rb
resources :orders, :path => 'orders'
Upvotes: 2
Views: 7973
Reputation: 575
OK, with help of @steel here is code.
routes.rb(changed start to symbol)
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 has the link on it.
<%= link_to "Send Order by email", :controller => "orders", :action => "send_order_mail", :id => @order.id %>
mailers/order_mailer.rb
class OrderMailer < ActionMailer::Base
add_template_helper(OrdersHelper)
default from: "[email protected]"
def order_send(order, client)
@order = order
@client = client
mail(to: "#{@client.email}", subject: "Your subject")
end
end
Upvotes: 5
Reputation: 12580
I'm not sure how to make your current method work, but there are several ways to do this. Here's one way I've used:
Set up your controller action:
orders_controller.rb
def send_order_mail
@parameters = Model.get_parameters
OrderMailer.name_of_action(@parameters).deliver
# redirect code here
end
Set up your route:
get send_order_mail, to: 'orders_controller#send_order_mail', as: :send_order_mail
Then make your link.
link_to 'Send mail', send_order_mail_path, class: "big-button"
Upvotes: 5