0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Railsチュートリアル11章】:idがnilになりNo route matchesが発生する

Posted at

エラー概要

Railsチュートリアル11章リスト11.24にて
ユーザー登録にアカウント有効化を追加後Minitestが通りませんでした。

users_controller.rb
class UsersController < ApplicationController
  .
  .
  .
  def create
    @user = User.new(user_params)
    if @user.save
      UserMailer.account_activation(@user).deliver_now
      flash[:info] = "Please check your email to activate your account."
      redirect_to root_url
    else
      render 'new', status: :unprocessable_entity
    end
  end
  .
  .
  .
end

エラー内容

ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"account_activations", :email=>"user@example.com", :id=>nil}, possible unmatched constraints: [:id]

原因

本来new_tokenメソッドで生成されるランダムな文字列が入るはずの:idがnilになっているためルーティングエラーが発生しているようです。

今回:idにあたるランダムな文字列を生成するnew_tokenメソッドを使用している箇所が怪しそうなので確認します。

user.rb
class User < ApplicationRecord
  .
  .
  # 有効化トークンとダイジェストを作成および代入する
  def create_activation_digest
    self.activation_digest = User.new_token
    self.activation_digest = User.digest(activation_token)
  end
end

self.activation_tokenとすべきところをself.activation_digestにしていました、、

修正すると無事テストが通りました。
@user.saveが実行された時点でインスタンス変数であるactivation_digestに値がセットされていないことが原因でした。

user.rb
class User < ApplicationRecord
  attr_accessor :remember_token, :activation_token
  before_save :downcase_email
  # before_create :create_activation_digest
  .
  .  

before_createで指定を忘れた場合も同様のエラーが発生します。

まとめ

同じ箇所でつまずいた方の参考に少しでもなれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?