Hartl的rails教程ch11:为什么我的account_activation邮件模板预览不起作用?

时间:2017-11-13 08:04:40

标签: ruby-on-rails ruby railstutorial.org

我正在讨论Hartl的rails教程,第11.2.1节Mailer模板,密码重置邮件的预览工作正常,但account_activation预览没有。即使我没有对代码进行任何更改,这个错误实际上也发生了变化,这令人困惑。但是,我目前收到的错误是

NoMethodError in Rails::Mailers#preview

Showing /home/ubuntu/workspace/sample_app/app/views/user_mailer/account_activation.html.erb where line #3 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #3)

<h1>Sample App</h1>

<p>Hi <%=@user.name %>,</p>

<p>
Welcome to the Sample App! Click on the link below to activate your account:

这是我的user_mailer.rb

class UserMailer < ApplicationMailer

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

  def account_activation
    @greeting = "Hi"

    mail to: "to@example.org"
  end

  def password_reset
    @greeting = "Hi"

    mail to: "to@example.org"
  end
end

account_activations_controller.rb(目前在教程中尚未指定代码)

class AccountActivationsController < ApplicationController
end

和错误来源account_activation.html.erb

<h1>Sample App</h1>

<p>Hi <%=@user.name %>,</p>

<p>
Welcome to the Sample App! Click on the link below to activate your account:
</p>

<%= link_to "Activate", edit_account_activation_url(@user.activation_token,
                                                    email: @user.email) %>

似乎无法识别用户的名字。为什么会这样? (注意:所有代码都是从教程中复制的,因此我对错误原因感到茫然) 感谢。

编辑:根据评论,确实有2个account_activation方法。我删除了第二个并保留了第一个。现在错误已更改为参数错误。

ArgumentError in Rails::MailersController#preview 
wrong number of arguments (given 0, expected 1)

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

此方法似乎在没有参数的以下文件中使用。

/sample_app/test/mailers/previews/user_mailer_preview.rb

class UserMailerPreview < ActionMailer::Preview

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/account_activation
  def account_activation
    user = User.first
    user.activation_token = User.new_token
    UserMailer.account_activation(user)
    UserMailer.account_activation
  end

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
  def password_reset
    UserMailer.password_reset
  end

end

1 个答案:

答案 0 :(得分:2)

在您的UserMailer中,您目前有account_activation方法的2个版本 - 一个采用user参数,另一个采用{0}}参数。在Ruby中,你可以在一个具有相同名称的类中使用2个方法,以便第二个方法将替换之前的方法。

我不熟悉本教程的所有内容,但似乎没有参数的方法来自本教程前面的方法,现在应该已经删除了。

然后,您需要检查您调用UserMailer.account_activation.deliver...的代码并将其更新为传递用户。

<强>更新

user_mailer_preview.rb中,您要拨打account_activation两次:

...
UserMailer.account_activation(user)
UserMailer.account_activation
...

应删除不带user的来电。