Help us understand the problem. What is going on with this article?

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を取得できます。

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした