0
0

More than 3 years have passed since last update.

twitter-omniauthのgemでつくるTwitterログイン機能のあるあるエラー4選とその対処法

Last updated at Posted at 2020-08-29

Ruby On RailsでTwitterログインによるユーザー管理機能を実装するときのあるあるエラー4選とその対処法です。

環境

  • mac OS Catalina 10.15.6
  • Ruby 2.6.3
  • Rails 6.0.3.2

メールアドレス認証

ユーザー管理機能のベースにはdeviseのgemを使います。
Twitterログイン機能の作成にはomniauth-twitterのgemを使います。

Gemfile
gem 'devise' 
gem 'omniauth' 
gem 'omniauth-twitter'
bundle install

参考:
deviseで新規登録時にメールを送る
RailsにDevise+OmniAuthでユーザ認証を実装する手順

エラー1: サインアップしようとするとエラーが出る

NameError in Devise::RegistrationsController#create\_ \_undefined local variable or method \`confirmed\_at' for #User: Did you mean? confirmed?

解決法

Userモデルに#confirmableのカラムを足す

user.rb
devise :confirmable

エラー2: Missing host to link to!が出る

Missing host to link to! Please provide the :host parameter, set default\_url\_options\[:host\], or set :only\_path to true\_ 

解決法

config > environment > development.rbでhostのurlを指定する

/config/environments/development.rb
  host = 'samplehost'
  Rails.application.routes.default_url_options[:host] = host

参考:RailsでMissing host to link to!が出たときに。model内でURL組み立てる場合の設定

エラー3: 新規登録/ログインボタンの押下後に、またdeviseのログイン画面が表示される(ログインページに戻ってしまう)

ユーザー情報をDBに登録できていないことによるエラーです。

解決法

  1. emailアドレスを自動で設定する処理を入れる
    参考:Devise内でomniauthのtwitter認証が完了してもレコードが格納されない
  2. emailアドレスをそもそも無視する
    参考: persist?がfalseになる原因。
  3. devise.rbから :validatable を削除する などのパターンがある。 
    参考:devise/omniauth login with twitter - validation failed: email can't be blank

1がおすすめ。

エラー4: ユーザーIDが取得できない

undefined method \`id' for nil:NilClass 

エラー原因:ログインできておらず、ユーザーIDがnullになっている
参考:undefined method `id' for nil:NilClassについて

解決法

current_userに値があるかどうかチェックする

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