Santosh Aryal Santosh Aryal - 7 months ago 18
Ruby Question

Rails mailer view template pass value send by a form

Its my first attempt to use the rails mailer to send email. I however is able to send plain emails but when I tried to pass the logged in user (current_user) name and params values send by the form I am getting the error. Undefined method 'params'.

payment_mailer.rb

class PaymentMailer < ApplicationMailer
def success(user)
mail(to: "#{user.first_name} #{user.last_name} <#{user.email}>", subject: "Payment Successful")
end
end


success.html.erb

<div class = "col-sm-12">
<h1>Payment Successful</h1>
<p>Dear <%= user.first_name %>, Thank you for being a part of our system<br>
Your invoice (#<%= params[:id] %>) has been generated.
</p>
</div>
<div class = "clearfix"></div>
<div class = "col-sm-6">
<table class = "table">
<thead>
<tr>
<th>Paid Ammount</th>
<th>Card Transaction Fee (2.9% + 0.30)</th>
<th>Credited Ammount</th>
</tr>
</thead>
<tbody>
<tr>
<td>&euro;<%= params[:amount] %></td>
<td></td>
<td></td>
</tr>
</tbody>
<h3>Total credited amount in your Account is: </h3>
</table>
</div>
<div class = "clearfix"></div>
</div>


payment_controller.rb

amount = params[:amount]
@user = current_user
netamt = (amount.to_f - ((amount.to_f*2.9)/100 + 0.30))
payment = @user.payments.create(:amount => netamt, :method => "Card", :txn_code => params[:stripeToken])
@user.update_attribute(:balance, @user.balance+netamt)
PaymentMailer.success(current_user).deliver_now


Please guide me.

Answer

Just change in your payment controller after the payment, do like that

PaymentMailer.success(payment).deliver_now

And in your mailer do

class PaymentMailer < ApplicationMailer
  def success(payment)
    @payment = payment
    @user = payment.user
    mail(to: "#{@user.first_name} #{@user.last_name} <#{@user.email}>", subject: "Payment Successful")
  end
end

and in your mailer template use

@payment.id #for payment id

@payment.amount #for amount

@user.first_name #for user name