Facebook と頻繁にやり取りする Rails アプリを作成します。私は、ユーザーが他のユーザーのプロフィールを見て、Facebook から引き出されたそれらのユーザーに関する情報を参照できるようにしたいと考えています。
私は omniauth-facebook と koala gems を使用しています。Ryan Bates の Railscasts on Facebook authentication と Facebook Graph API をフォローして、自分の現在地を把握しました。
ユーザーの Facebook 情報をデータベースに保存する必要はありませんが、それが唯一の方法のようです。そうしないと、ログアウトした可能性のある別のユーザーのプロフィール ページを表示しようとすると、 : "Koala::Facebook::AuthenticationError in Profiles#show"
type: OAuthException, code: 190, error_subcode: 467, message: Error validating access token: The session is invalid because the user logged out. [HTTP 400]
.
ユーザーがログアウトした場合でも、Facebook からこのデータを取り込む方法はありますか?
必要なコードは次のとおりです。
ユーザー.rb:
class User < ActiveRecord::Base
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.image = auth.info.image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
def facebook
@facebook ||= Koala::Facebook::API.new(oauth_token)
block_given? ? yield(@facebook) : @facebook
rescue Koala::Facebook::APIError
logger.info e.to_s
nil
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
redirect_to feed_path
end
def destroy
session[:user_id] = nil
redirect_to root_url
end
end
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
end
helper_method :current_user
end
profile_controller.rb
class ProfilesController < ApplicationController
def show
@user = User.find(params[:id])
end
end
profile_helper.rb:
module ProfilesHelper
def facebook_profile_info
@user.facebook.get_object("#{@user.uid}",fields:'gender, locale, bio, birthday,
picture, relationship_status')
end
end
また、これらのタスクを達成するための、私が向かっている軌道よりも優れた方法について提案があれば、歓迎します。