How To Get User Information From Facebook To Rails Application?

With Facebook’s Graph API and the creation of the Open Graph protocol, it is now easier then ever before to read and write data from facebook to rails application and back to the “social graph”. Here’s a few of the possibilities:

  • You could turn your webpage into a fully-featured Facebook-like page, just like if you were inside Facebook.
  • You can give your users the ability to sign in with their Facebook credentials and customize their experience with parameters taken from their Facebook profiles.
  • You could add a Like button to every object in your page such as images, songs, articles, etc., and tell your users which friends of theirs have liked your content.

Steps to create application and fetch information

A facebook app_id, and api_secret_key is needed

go to the link

1. Create new app on facebook
  • Give app name(example: sample_app)

  • then we need to fill following information

  • App domain: localhost

  • website url: http://localhost/3000/

On the same page we can find App Id & App Secret . It looks like

App ID: 378271044441102

App Secret: 567772fd2bef4dda7a404b02r4567c758

2. Create Rails application

The following are the steps to create rails application

  • rails new facebook_app
  • sudo gem install fb_graph
  • add to Gemfilegem “fb_graph”
  • sudo bundle install
  • create index page to fb_loginrails generate controller pages index
  • set index to root page in config/routes.rbroot :to => “pages#home”
  • create authentication for app(simple authentication)
  • creating facebook controller and facebook model with :Identifier => string:access_token =>string
  • rails generate scaffold facebook identifier:string access_token:string
  • rails generate controller dashboard show
  • In pages controller redirect the page to dashboard:show if it is authenticated alreadycontroller/pages_controller.rb

indice déf

redirect_to dashboard_url if authenticated?


If not authenticated then root_path will be loaded ie. pages/index, create fb_login in this page to authebticate.

<% if authenticated? %>

<p><%= link_to “Logout”, facebook_path, :method => :delete %></p>

<% else %>

<fb:login-button length=”long” onlogin=”location.href = ‘<%= facebook_path %>'” scope=”<%=

Facebook.config[:scope] %>”> </fb:login-button>

<% fin %>

3. Paste the following script code(for facebook login button)

<script src=””></script>



appId: “<%= Facebook.config[:client_id] %>”,

cookie: true,

xfbml: true,

oauth: true,

status: true



<script type=”text/javascript”>

$(function () {

<% if flash[:error] %>


title: “<%= flash[:error][:title] %>”,

text : “<%= flash[:error][:message] %>”,

image: “<%= flash[:error][:image] %>”,

time : 5000


<% elsif flash[:notice] %>


title: “<%= flash[:notice][:title] %>”,

text : “<%= flash[:notice][:message] %>”,

image: “<%= flash[:notice][:image] %>”,

time : 3000


<% fin %>



The above code is used to authenticate user through facebook, after authenticating user should redirect to dashboard url to show his information fetched from facebook. some facebook settings should be code in facebook model, and controller.

In controller/facebook_controller.rb.

before_filter :require_authentication, :only => :destroy

rescue_from Rack::OAuth2::Client::Error, :with => :oauth2_error

# handle Facebook Auth Cookie generated by JavaScript SDK

définitivement montrer

auth = Facebook.auth.from_cookie(cookies)

authenticate Facebook.identify(auth.user)

redirect_to dashboard_url


# handle Normal OAuth flow: start

définitivement nouveau

client = Facebook.auth(callback_facebook_url).client

redirect_to client.authorization_uri(

:scope => Facebook.config[:scope]



# handle Normal OAuth flow: callback

créer par défaut

client = Facebook.auth(callback_facebook_url).client

client.authorization_code = params[:code]

access_token = client.access_token! :client_auth_body

user =

authenticate Facebook.identify(user)

redirect_to dashboard_url


définitivement détruire


redirect_to root_url



def oauth2_error(e)

flash[:error] = {

:title => e.response[:error][:type],

:message => e.response[:error][:message]


redirect_to root_url


4. Paste this code in facebook.rb

def profile

@profile ||=


class << self

extend ActiveSupport::Memoizable

def config

@config ||= if ENV[‘fb_client_id’] && ENV[‘fb_client_secret’] && ENV[‘fb_scope’] && ENV[‘fb_canvas_url’]


:client_id => ENV[‘fb_client_id’],

:client_secret => ENV[‘fb_client_secret’],

:scope => ENV[‘fb_scope’],

:canvas_url => ENV[‘fb_canvas_url’]





rescue Errno::ENOENT => e

raise“config/facebook.yml could not be loaded.”)


def app config[:client_id], :secret => config[:client_secret]


def auth(redirect_uri = nil) config[:client_id], config[:client_secret], :redirect_uri => redirect_uri


def identify(fb_user)

_fb_user_ = find_or_initialize_by_identifier(fb_user.identifier.try(:to_s))

_fb_user_.access_token = fb_user.access_token.access_token!




Now we are ready to get user info if he authenticated, once he authenticate page will redirect to dashboard_url,

code in controller/dashboard_controller.rb

before_filter :require_authentication k

view for dashboard/show.html.erb

<h2>User Profile</h2>



<dd><%= current_user.profile.username %></dd>


<dd><%= %></dd>

<dt>First Name</dt>

<dd><%= current_user.profile.first_name %></dd>

<dt>Middle Name</dt>

<dd><%= current_user.profile.middle_name %></dd>

<dt>Last Name</dt>

<dd><%= current_user.profile.last_name %></dd>


<dd><%= current_user.profile.gender %></dd>


<dd><%= link_to, %></dd>


<dd><%= %></dd>


<dd><%= current_user.profile.about %></dd>


<dd><%= current_user.profile.birthday %></dd>


The above code is to show user information.

5. Finally create facebook.rb file in config

development: &defaults

client_id: “your facebook app_id”

client_secret: “facebook secret id”

scope: user_about_me,friends_about_me,user_activities,friends_activities,user_birthday,







<<: *defaults


<<: *defaults

Prenez contact avec nous.

Abonnez-vous pour les dernières mises à jour

Articles Similaires

1 réflexion sur “How To Get User Information From Facebook To Rails Application?”

  1. An impressive share! I’ve just forwarded this onto a colleague who has been conducting
    a little research on this. And he in fact bought me breakfast due to the fact
    that I stumbled upon it for him… lol. So let me reword
    this…. Thanks for the meal!! But yeah, thanks for spending some time to talk about this matter here on your blog.

Laissez un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *