Rails邮件程序视图模板传递值由表单发送

时间:2016-04-27 12:43:33

标签: ruby-on-rails ruby actionmailer mailer

我第一次尝试使用rails邮件发送电子邮件。然而,我能够发送普通的电子邮件,但当我尝试传递登录的用户(current_user)名称和由表单发送的参数值时,我收到错误。未定义的方法'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

请指导我。

2 个答案:

答案 0 :(得分:2)

付款后只需更改付款控制器,就像那样

PaymentMailer.success(payment).deliver_now

在您的邮件中

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

并在您的邮件模板中使用

@payment.id #for payment id

@payment.amount #for amount

@user.first_name #for user name

答案 1 :(得分:0)

未在邮寄者的上下文中定义控制器对象,例如paramscurrent_user

您需要在用户上设置这些值,或者在邮件程序方法中将其作为附加参数传递。您还需要分配实例变量以在邮件程序视图中访问这些值(与将控制器中定义的实例变量传递给ActionView的原理相同)。

class PaymentMailer < ApplicationMailer
    def success(user, invoice_id, amount)
        @invoice_id = invoice_id
        @amount = amount

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

但是,似乎amountiduser都是payment对象的变量,所以它听起来像你真正应该传递的对象{ {1}}使用payment方法,而不是success。这可能吗?