Search code examples
ruby-on-railsrubyruby-on-rails-5mailer

Rails 5 - Instance variables not available in email body


I set up an email to send right after the purchase but in the view of the email the variables don't appear. Any idea why?

user_mailer

def successful_payment(user, product)
    @user = user
    @product = product
    mail(:to => user.email,
        :subject => "Confirmation of payment #{product.name}")
end

payments_controller

def create
    @product = Product.find(params[:product_id])
    @user = current_user
    token = params[:stripeToken]
    # Create the charge on Stripe's servers - this will charge the user's card
    begin
      charge = Stripe::Charge.create(
        :amount => (@product.price * 100).to_i, # amount in cents, again
        :currency => "eur",
        :source => token,
        :description => params[:stripeEmail]
      )
      if charge.paid
        Order.create(product_id: @product.id, user_id: @user.id, total: @product.price)
        UserMailer.successful_payment(@user, @product).deliver_now
      end

template

<table style="max-width:800px;margin:auto;padding:20px;box-shadow: 0px 1px 4px #000;margin-top:40px;background-color:#f7f7f4;">
  <tbody style="text-align:center;margin:auto;">
    <tr>
      <td><h2 style="color:#625F5F;font-family: 'Open Sans', sans-serif;">Hello <% @user.first_name %></h2></td>

The name of the user won't appear.


Solution

  • It's an error in the template. The syntax is <%= ... %> to output text. <% ... %> only runs the code without outputting anything.

    So the solution is:

    <%= @user.first_name %>