実現したいこと
omniauth-google-oauth2を使用したログインフォームの作成 ↓のようなイメージです
###前提
モデル: Host
Host(id: integer, name: string, password_digest: string, created_at: datetime, updated_at: datetime, admin: boolean, provider: string, uid: string, image: string, oauth_token: string, oauth_expires_at: datetime, email: string)
コントローラー: session
のような構成になっております。
###コード
session_controller.rb
class SessionController < ApplicationController skip_before_action :login_required def new end def create host = Host.find_by(name: session_params[:name]) if host&.authenticate(session_params[:password]) session[:host_id] = host.id redirect_to root_path else render :new end end #google認証 def create_g host = Host.from_omniauth(request.env["omniauth.auth"]) if host.save session[:host_id] = host.id redirect_to root_path else render :new end end def destroy reset_session redirect_to root_path end private def session_params params.require(:session).permit(:name, :password) end
###session/new.html.erb
<div class="container"> <%= form_with scope: :session, local: true do |f| %> <%= f.label :name, '名前'' %> <%= f.text_field :name, class: 'form-control',id: 'session_name'%> <%= f.label :password, 'パスワード' %> <%= f.password_field :password, class: 'form-control',id: 'session_password'%> <%= f.submit 'ログイン', class: 'btn btn-info' %> <% end %> <%= link_to "googleアカウントでログイン", "/auth/google_oauth2", id: "sign_in", method: :post %>
###config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'] end
###models/host.rb
class Host < ApplicationRecord def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |host| host.provider = auth.provider host.uid = auth.uid host.name = auth.info.name host.email = auth.info.email host.image = auth.info.image host.oauth_token = auth.credentials.token host.oauth_expires_at = Time.at(auth.credentials.expires_at) return host end end end
発生している問題・エラーメッセージ
<%= link_to "googleアカウントでログイン", "/auth/google_oauth2", id: "sign_in", method: :post %>)
######上記リンクを踏んでgoogleアカウントでログインを実施するとhostの中身が
######下記のようにid:nilとなってしまいます。
######host.idでsessionを作成しているため、idがnilだとログイン出来ません
※不必要なところは略としてあります
id: nil, name: "略", password_digest: nil, created_at: nil, updated_at: nil, admin: false, provider: "google_oauth2", uid: "略", image: "略", oauth_token: "略", oauth_expires_at: Mon, 22 Jul 2019 00:29:44 JST +09:00, email: "略"
###質問
・idをnilではなくすにはどのようにしたら良いのでしょうか?
・または,idの問題と関係なくスマートにログインフォーム実装する方法ありますでしょうか?
補足情報(FW/ツールのバージョンなど)
ruby 2.4.5p335 (2018-10-18 revision 65137) [x64-mingw32]
Rails 5.2.3

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。