Rails::MailersController#preview nil:NilClass 的未定义方法 `activation_token=' 中的 NoMethodError

NoMethodError in Rails::MailersController#preview undefined method `activation_token=' for nil:NilClass

似乎无法为此找到有效的答案。我正在学习 Rails 教程的第 10 章第 10.1.2 节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码 copy/pasted 放入相关文件中,但到目前为止还无法看出我输入的内容与教程中的内容之间的区别。到目前为止,建议是在函数定义中添加或删除参数 user,但这并没有解决问题。触发错误的 url 是 http://localhost:3000/rails/mailers/user_mailer/account_activation. http://localhost:3000/rails/mailers/user_mailer/ is having no issues, and neither is http://localhost:3000/rails/mailers/user_mailer/password_reset(我还没有对其进行任何自定义)。我错过了什么?

这是错误:

    NoMethodError in Rails::MailersController#preview
    undefined method `activation_token=' for nil:NilClass

提取的来源:

def account_activation
  user = User.first
  user.activation_token = User.new_token # highlighted line
  UserMailer.account_activation(user)
end

据我所知,这里涉及的文件有:

user_mailer.rb:

     class UserMailer < ApplicationMailer

       # Subject can be set in your I18n file at config/locales/en.yml
       # with the following lookup:
       #
       #   en.user_mailer.account_activation.subject
       #
       def account_activation(user)
         @user = user
         mail to: user.email, subject: "Account activation"
       end

       def password_reset
         @greeting = "Hi"

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

user_mailer_preview.rb:

     # Preview all emails at http://localhost:3000/rails/mailers/user_mailer
     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)
       end

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

     end

development.rb:

    Rails.application.configure do

      config.cache_classes = false

      # Do not eager load code on boot.
      config.eager_load = false

      # Show full error reports and disable caching.
      config.consider_all_requests_local       = true
      config.action_controller.perform_caching = false

      # Don't care if the mailer can't send.
      config.action_mailer.raise_delivery_errors = true
      config.action_mailer.delivery_method = :test
      host = 'localhost:3000'
      config.action_mailer.default_url_options = { host: host }

      # Print deprecation notices to the Rails logger.
      config.active_support.deprecation = :log

      # Raise an error on page load if there are pending migrations.
      config.active_record.migration_error = :page_load

      # Debug mode disables concatenation and preprocessing of assets.
      # This option may cause significant delays in view rendering with a large
      # number of complex assets.
      config.assets.debug = true

      # Asset digests allow you to set far-future HTTP expiration dates on all assets,
      # yet still be able to expire them through the digest params.
      config.assets.digest = true

      # Adds additional error checking when serving assets at runtime.
      # Checks for improperly declared sprockets dependencies.
      # Raises helpful error messages.
      config.assets.raise_runtime_errors = true

      # Raises error for missing translations
      # config.action_view.raise_on_missing_translations = true
    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) %>

account_activation.text.erb: 嗨 <%= @user.name %>,

    Welcome to the Sample App. Click on the link below to activate your account:

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

user.rb:

    class User < ActiveRecord::Base
      attr_accessor :remember_token, :activation_token
      before_save   :downcase_email
      before_create :create_activation_digest
      validates :name,  presence: true, length: { maximum: 50 }
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
      validates :email, presence: true, length: { maximum: 255 },
                        format: { with: VALID_EMAIL_REGEX },
                        uniqueness: { case_sensitive: false }
      has_secure_password
      validates :password, length: { minimum: 6 }, allow_blank: true

      # Returns the hash digest of the given string.
      def User.digest(string)
        cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                      BCrypt::Engine.cost
        BCrypt::Password.create(string, cost: cost)
      end

      # Returns a random token
      def User.new_token
        SecureRandom.urlsafe_base64
      end

      # Remembers a user in the database for use in persistent sessions
      def remember
        self.remember_token = User.new_token
        update_attribute(:remember_digest, User.digest(remember_token))
      end

      # Returns true if the given token matches the digest.
      def authenticated?(remember_token)
        return false if remember_digest.nil?
        BCrypt::Password.new(remember_digest).is_password?(remember_token)
      end

      # Forgets a user.
      def forget
        update_attribute(:remember_digest, nil)
      end

      private

        # Converts email to all lower-case.
        def downcase_email
          self.email = email.downcase
        end

        # Creates and assigns the activation token and digest.
        def create_activation_digest
          self.activation_token  = User.new_token
          self.activation_digest = User.digest(activation_token)
        end
    end

哇,经过大量调试和混淆后发现了一个非常简单的问题:我没有登录,也没有为那些试图在未登录时访问该页面的人定义任何类型的错误消息(因此 user.activation_token 方法触发 Nil:NilClass 错误)。这似乎是为什么 TDD 可以提供大量帮助的一个很好的例子。

不确定是不是您的登录问题,而是没有用户。

你 运行 bundle exec rake db:seed 填充了吗?同样在您的控制台中检查您的数据库是否按预期填充...如果它没有检查您的 "seed.rb" 文件并在创建用户的部分确保 activated: true 存在,如下所示:

User.create!(name:  "Example User",
             email: "testing@akqa.com",
             password: "foobar",
             password_confirmation: "foobar",
             admin: true,
         **  activated: true,
             activated_at: Time.zone.now)

你上面提到的错误,'activation_token=' for nil:NilClass看起来实际上是因为没有用户。

虽然您提到了您 "logged in" 您实际上可能刚刚重新注册,因此创建了使此功能正常工作所需的用户。希望这对您有所帮助!

如果它和我一样的错误,你的数据库没有数据并且 user.first 检索 NIL 比下一行不起作用。 检查你的种子文件和你的数据库。