Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@sayama0402

Rails omniauth-facebookでFirst_nameとLast_name、Genderを取得する

More than 3 years have passed since last update.

前提

omniauth-facebookでfacebookログイン自体は完成していること(順序逆ですが、そのうちFacebookログインについても書きます)。

やりたいこと

デフォルトでは取得出来ないFacebookログイン時にuserのFirst_nameとLast_name、Genderを取得する。

実装

// models/user.rb
def self.from_omniauth(auth)
    user = User.where('email = ?', auth.info.email).first
    if user.blank?
      user = User.new
    end
    //ここにbinding.pryAPIから何が取得できているか確認しながら作業するのがオススメです。
    user.facebook_uid   = auth.uid
    user.name  = auth.info.name
    user.email = auth.info.email
    user.first_name = auth.extra.raw_info.first_name
    user.last_name = auth.extra.raw_info.last_name
    user.gender = auth.extra.raw_info.gender
    user.facebook_icon  = auth.info.image
    user.facebook_token      = auth.credentials.token
    user.facebook_expires_at = Time.at(auth.credentials.expires_at)
    user
  end

modelのuser.rbに以下を追加します。
user.first_name = auth.extra.raw_info.first_name
user.last_name = auth.extra.raw_info.last_name
user.gender = auth.extra.raw_info.gender
※ usersテーブルにfirst_namelast_namegenderカラムを作っていない場合は、
rails g migration AddColumnToUsers first_name last_name genderとすればカラムを作成できます。
コメントでも書きましたが、binding.pryで処理を止めて、authとpryに入力すれば取得しているデータを確認出来るので、いいかと思います。

# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET_KEY'], info_fields: 'first_name, last_name, gender'
end

環境変数の後にinfo_fieldsを追加してあげます。

以上でfirst_nameとlast_name、genderを取得できます。

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
sayama0402
Javascript(Riot.js / Vue / React / Nodejs) / PHP(Wordpress, cakePHP, Laravel) / Ruby(Ruby on Rails) / Python(Django) / SQL / Linux / Swift / Docker / AWS / Serverless

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?