質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Q&A

解決済

1回答

1115閲覧

本番環境で devise を利用しsign upをした時 Mysql2::Error: Unknown column 'confirmation_token'

Midori-Gift

総合スコア1

Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

0グッド

0クリップ

投稿2021/09/20 02:47

編集2021/09/20 10:47

本番環境で devise を利用しsign upをした時 Mysql2::Error: Unknown column 'confirmation_token'

Ruby on Railsで簡単な投稿ができるWebアプリケーションを作成中です。

ローカル環境ではDBにsqlite3 を利用し、サインアップが可能だったのですが、本番環境でMySQLを利用して同様の操作をした際に
マイグレーションファイルで設定していないはずのカラムでUnknown column と指摘が入りました。

以下その時のエラーです。

発生している問題・エラーメッセージ

ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'confirmation_token' in 'field list': INSERT INTO `users` (`email`, `encrypted_password`, `confirmation_token`, `confirmation_sent_at`, `name`, `created_at`, `updated_at`) VALUES ('okome@icloud.com', '$2a$12$48oAZDbUrknYnXOLfwwU0.mM80AkSXLRH3XtPSPkBw2apbTsxV0DW', '_ueaoLWR9ZcPHxxxpFBw', '2021-09-20 01:52:10', 'takeshikun', '2021-09-20 01:52:10', '2021-09-20 01:52:10')):

該当のソースコード

ruby

1デバイスを使用しているマイグレーションファイル 2 3# frozen_string_literal: true 4 5class DeviseCreateUsers < ActiveRecord::Migration[5.2] 6 def change 7 create_table :users do |t| 8 ## Database authenticatable 9 t.string :email, null: false, default: "" 10 t.string :encrypted_password, null: false, default: "" 11 12 ## Recoverable 13 t.string :reset_password_token 14 t.datetime :reset_password_sent_at 15 16 ## Rememberable 17 t.datetime :remember_created_at 18 19 ## Trackable 20 # t.integer :sign_in_count, default: 0, null: false 21 # t.datetime :current_sign_in_at 22 # t.datetime :last_sign_in_at 23 # t.string :current_sign_in_ip 24 # t.string :last_sign_in_ip 25 26 ## Confirmable 27 # t.string :confirmation_token 28 # t.datetime :confirmed_at 29 # t.datetime :confirmation_sent_at 30 # t.string :unconfirmed_email # Only if using reconfirmable 31 32 ## Lockable 33 # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 34 # t.string :unlock_token # Only if unlock strategy is :email or :both 35 # t.datetime :locked_at 36 37 t.string :name 38 t.string :image_id 39 40 41 t.timestamps null: false 42 end 43 44 add_index :users, :email, unique: true 45 add_index :users, :reset_password_token, unique: true 46 # add_index :users, :confirmation_token, unique: true 47 # add_index :users, :unlock_token, unique: true 48 end 49end 50
# devise/registrations/new.html.erb(form_withの行以外はデフォルト) <h2>Sign up</h2> <%= form_with model: @user, url: user_registration_path, local: true do |f| %> <%= render "devise/shared/error_messages", resource: resource %> <!--ユーザー登録時に名前を追加--> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name, autofocus: true %> </div> <!-- --> <div class="field"> <%= f.label :email %><br /> <%= f.email_field :email, autofocus: true, autocomplete: "email" %> </div> <div class="field"> <%= f.label :password %> <% if @minimum_password_length %> <em>(<%= @minimum_password_length %> characters minimum)</em> <% end %><br /> <%= f.password_field :password, autocomplete: "new-password" %> </div> <div class="field"> <%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation, autocomplete: "new-password" %> </div> <div class="actions"> <%= f.submit "Sign up" %> </div> <% end %> <%= render "devise/shared/links" %>

試したこと

・本番環境で使われているマイグレーションファイルと相違無いかの確認。
・エラーで要求されたカラムのコメントアウトを外して一度migrateしてみる。(入力メールアドレスに本登録用のURLを送信→そのURLから登録完了という処理になるが今回は利用したくない)

・本番環境にてMySQLに入り、show tableでテーブル内に余計な情報が入っていないかの確認

補足情報(FW/ツールのバージョンなど)


※補足としてですが、この前にactionmailerを利用し、
メールアドレスから本登録を行ってもらおうとしていましたが、断念しました。
そのときの

20210910073029_devise_create_users.rb 内 ## Confirmable # t.string :confirmation_token # t.datetime :confirmed_at # t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable

これらのコメントアウトを外して
$bundle exec rails db:migrate RAILS_ENV=production を実行しています。

もちろんその後
$RAILS_ENV=production DISABLE_DATABASE_ENVIRONMENT_CHECK=1 bundle exec rails db:drop
で一度DBのリセットを行ってから、再度migrateを試みています。

※ご指摘頂けたので追加します、その時のモデルファイルです。@neko_daisuki より 2021/09/20

当時のモデルです(user.rb) class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable # 断念する前はここに :confirmable と追加していました! # 適切なメールアドレスだけが登録できるように正規表現追加 TRUE_EMAIL = /[\w]+@[a-z]+.[a-z]+.?[a-z]+/ validates :email, presence: true, format: { with: TRUE_EMAIL} has_many :posts, dependent: :destroy has_many :post_comments, dependent: :destroy has_many :favorites, dependent: :destroy # ユーザーアイコン設定用 attachment :profile_image end

何か影響があるとしたらここかな?と考えているのですが全く解決できていません。


Gemfileは以下の通りです。

# Gemfile source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.3' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.2.6' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use Puma as the app server gem 'puma', '~> 3.11' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'mini_racer', platforms: :ruby # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 4.0' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use ActiveStorage variant # gem 'mini_magick', '~> 4.8' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.1.0', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', '>= 2.15' gem 'selenium-webdriver' # Easy installation and use of chromedriver to run system tests with Chrome gem 'chromedriver-helper' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] # ユーザー承認機能のために追加 2021/9/10 gem 'devise' # ファイルをアップロード出来るように追加 (画像用) 2021/9/10 gem "refile", require: "refile/rails", github: 'manfe/refile' gem "refile-mini_magick" # 画像のリサイズが行える # 今後たくさんのユーザーが利用する想定でページング機能を追加 2021/09/12 gem 'kaminari','~> 1.2.1' # デザイン・レイアウトのため追加 2021/09/13 gem 'bootstrap', '~> 4.5' gem 'jquery-rails' gem 'font-awesome-sass', '~> 5.13' # MySQLの利用と環境変数利用のため追加 2021/09/18 gem 'dotenv-rails' group :production do gem 'mysql2' end

ご指摘や不明点などありましたら是非お願いします!

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

neko_daisuki

2021/09/20 10:11

「メールアドレスから本登録」を追加しようとしたときに user.rb も編集していませんか?
Midori-Gift

2021/09/20 10:38 編集

neko_daisukiさん、返答ありがとうございます!! user.rbの編集、確かに行っております! 現状は下記の通りですが ''「メールアドレスから本登録」を追加しようとしたとき'' との違いは()内の記述を追加していたことです! ``` class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable (ここに :confirmable と追加していました!!) # 適切なメールアドレスだけが登録できるように正規表現追加 TRUE_EMAIL = /[\w]+@[a-z]+\.[a-z]+\.?[a-z]+/ validates :email, presence: true, format: { with: TRUE_EMAIL} has_many :posts, dependent: :destroy has_many :post_comments, dependent: :destroy has_many :favorites, dependent: :destroy # ユーザーアイコン設定用 attachment :profile_image end ``` 修正しておきます! また回答に添えていない、伝わりにくい等ありましたらお願いします!
neko_daisuki

2021/09/20 10:49

現在 confirmable が含まれていないのにこのエラーはおかしいですね。 本番環境に ssh で接続するなどして cat で user.rb を見ても、confirmable は含まれていませんか? 含まれていなければ rails のプロセスを全部 kill して再起動してみるとか・・・
Midori-Gift

2021/09/20 11:22 編集

返信、本当にありがとうございます! 下記、本番本番環境に潜って catコマンドを実行したときの出力結果となっています! ``` class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable # 適切なメールアドレスだけが登録できるように正規表現追加 TRUE_EMAIL = /[\w]+@[a-z]+\.[a-z]+\.?[a-z]+/ validates :email, presence: true, format: { with: TRUE_EMAIL} has_many :posts, dependent: :destroy has_many :post_comments, dependent: :destroy has_many :favorites, dependent: :destroy # ユーザーアイコン設定用 attachment :profile_image end ``' この後返信頂いたkillコマンドや 本番環境の再起動などやっていければと思います! 改めて、返信ありがとうございます!
Midori-Gift

2021/09/20 11:29 編集

neko_daisuki さんから頂いた -------------------------------------------------------------------------------------------- 2021/09/20 19:49 現在 confirmable が含まれていないのにこのエラーはおかしいですね。 本番環境に ssh で接続するなどして cat で user.rb を見ても、confirmable は含まれていませんか? 含まれていなければ rails のプロセスを全部 kill して再起動してみるとか・・・ -------------------------------------------------------------------------------------------- こちらの返信から無事解決することができました! 本当にありがとうございます! しかし、私は解決に導いて頂いただけですので ''自己解決’’はできていません、ですのでneko_daisukiさんに確認して頂いた後、 ''neko_daisukiさんの回答''として是非お願いします! 今回の返信の内容をベストアンサーとさせて頂きます!!
neko_daisuki

2021/09/20 12:03

おめでとうございます。 どうやって解決されたのでしょうか? それを回答として貼り付けたいと思います。
Midori-Gift

2021/09/20 13:33

返信遅れてすみません! 重ねて言葉足らずですみませんでした! 今回は初めに railsのプロセス(Pumaを停止) →本番環境でのDBのリセット →再度本番環境にてDBのmigrate →開発しているWebアプリ内でユーザーの登録(ローカルと同じ挙動に) という順で解決しました! 具体的なコマンド順としては上から $ sudo kill $(cat tmp/pids/puma.pid)       ↓ $ RAILS_ENV=production DISABLE_DATABASE_ENVIRONMENT_CHECK=1 bundle exec rake db:drop       ↓ (※$rails db:create RAILS_ENV=productionは今回は既に作っていたのでせず)       ↓ $ rails db:migrate RAILS_ENV=production ※この時点で恐らく解決、最後にサインイン なぜマイグレートから外したカラムが入っているのかばかり考えていると 今回のようにハマってしまいますね... 正解に導いて下さり、本当にありがとうございました! なんと言いますか結果的に拍子抜けで申し訳ありません。 改めまして、私を救って頂きありがとうございます。
guest

回答1

0

ベストアンサー

たぶんですが、puma を再起動した時点で解決していたと思います。
confirmable を含むコードから起動された puma が生きていて、一方で DB には confirmation_token カラムが存在せず、
それでこのエラーを発生させたのではないでしょうか。

capistrano を使っているなら、運用開始前に bundle exec cap production puma:restart
pid が変更されるかなど確認しておくと、運用が始まってからも安心できると思います。

投稿2021/09/20 13:58

neko_daisuki

総合スコア2090

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Midori-Gift

2021/09/20 14:03

ありがとうございます。 capistranoについて知らないので調べてみますね! また、教えて頂いたコマンドについても調べさせてもらいます 今回は一通り付き合って頂き本当にありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問