Sample Koala-Facebook Ruby on Rails App

Back on my old post: “Ruby on Rails and Facebook API (Koala): Basic Example” there was a request for either sample code, or more detail. I’ve setup an app in Github: “Sample Koala Rails Test.”. You can get that code by putting the following on your server:

git clone git://

Or, just read it online at GitHub. Please remove my app id and secret if you implement.

Important Step
Setup your Facebook app for local development on your computer. To do this, set the site_url to “http://localhost:3000/” (or whatever port you are running your Rails server).

1. Create your own Facebook app.

2. Copy the application id, secret, and url into the /config/initilizers/constants.rb file. Don’t use mine!

3. Run the server: “rails s”

4. Access in a browser http://localhost:3000

5. Click the “authenticate this app” button, and you will go through the authentication flow for gaining credentials to Facebook data, as a user.

6. The next view displays your recent statuses.

What’s going on?

Well, quite a lot, it turns out.

You’re setting up authentication between the Facebook server, your local application, and the user. It’s well explained in the Facebook Developer Authentication Guide, though written for PHP and JavaScript developers, mainly. What we’re doing is “Facebook Application” authentication, even though we’re not hosting it inside an iFrame on Facebook itself (which is totally possible, I just didn’t do it for simplicity’s sake).

First, we setup a Koala object

session[:oauth] =, APP_SECRET, SITE_URL + ‘/home/callback’)

Passing to it our Facebook application constants. We will use this session variable throughout the app.
Next, we derive a “authentication url”, and pass to it a string that represents the access we’d like to have. In this example, it’s “read_stream”- accessing the user’s statuses (chart of Facebook permissions).

@auth_url =  session[:oauth].url_for_oauth_code(:permissions=>"read_stream")

Koala takes this information and creates an “auth_url”- a link to the Facebook auth services. We use this variable in our index.html.erb view, to direct the user to authenticate. Facebook checks the user to see if they’re logged in and already authorized for the app. If not, it leads them through a series of screens to explain and request permission. You noticed when we setup the Koala session variable “oauth”, that we included a redirect uri. This is where we want the user to land after authentication. In rails, it’s a controller/method combination. We’re sending them, in this example, to “home/callback.”

In the callback method, the authentication is still not complete. We receive a “code” in the GET string, which we send to the “oauth” session object.

if params[:code]
     # acknowledge code and get access token from FB
     session[:access_token] = session[:oauth].get_access_token(params[:code])

Koala sends this to Facebook (largely in the background) requesting the final token, the “access token.” Then, we send this access token to Koala object, which then enables us to use the Koala methods to retrieve data from Facebook.

We query the Facebook data with the “get_object” method, and pass to it two arguments, first the object (me) and the connection, “statuses.” It is well explained in Facebook’s description of the User graph object. Farther down you can read about the other available connections, and, you can query the data through the Explorer Tool – very handy.

@api =[:access_token])
@graph_data = @api.get_object("/me/statuses", "fields"=>"message")

The result is a hash, “GraphCollection.” I minimized the data result by setting the specific fields in “statuses” to return. That is the second argument in “get_object” method, “fields”=>”message”. This simplifies the code and speeds up the query.

Depending on how you want to build your app- using session objects or passing the “code” GET parameter around- depends on how you are hosting your app and various browser issues. Some opt for JavaScript session management, cookie, or re-authenticating with the Code element in the query string each time. This sample app is simply two views so it’s relatively simple.

Koala’s a great lightweight framework for Facebook. In this example, I’m using 1.3.0. This is how I created the sample:

1. Created a simple rails app, “rails new koalatest”
2. Added “”koala”,”1.3.0″ to the Gemfile, ran update bundle.
3. Created “constants.rb” file in /config/initializers, and updated with my new app id and secret.
4. Copied in the two methods- index and callback- from another app I have.
5. Added the two routes, and the root route.
6. Spent quite a bit of time futzing with CSS and the View (graphcollection isn’t very intuitive)

Enjoy, and if you have any questions please feel free to comment!

More reading
Realtime facebook updates with Rails, Koala, and Resque
Rails 3 Sample App
Developing Facebook Apps Using Koala


  1. Comment by PrasannaKrishnamoorthy

    Posted on March 29, 2012 at 2:48 pm


    Thanks for the test app – it's greatly appreciated.

    I'm having some trouble though – I keep getting a connection timeout

    Errno::ECONNRESET in HomeController#callback
    Connection reset by peer – SSL_connect

    I haven't been able to nail this although I've done quite a bit of googling.

    Basic SSL through faraday works fine – I tested that separately.

    Any suggestions would be greatly appreciated :)


  2. Comment by banane

    Posted on March 29, 2012 at 6:01 pm

    Prasanna, when do you get the error- when trying to authenticate? FB passes a “code” that we're capturing in the callback. Try to print that out to log. Feel free to copy in your code here or provide a gist link if you want more detailed help.


  3. Comment by PrasannaKrishnamoorthy

    Posted on March 29, 2012 at 6:09 pm

    Thanks Anna!

    The line on which SSL is getting a connection reset by peer is

    > home_controller:17  session[:access_token] = session[:oauth].get_access_token(params[:code])

    That's from the rails error page – parameters.

    I've made no changes to your code, except to add the FB appid and secret.

    I am a total newbie to rails/ruby – I've worked in PHP/Symfony, C, etc before though.

  4. Comment by banane

    Posted on March 29, 2012 at 6:22 pm

    Interesting. Couple of questions- which Koala do you have? They went through a recent upgrade and I haven't tested it.

    Also, make sure your FBapp settings are like mine:

    Since it's getting back to the callback method witha “code” it makes me think that FB is configured right. We need to get Koala to send out an auth error, that could be a variety of things. The state that it's erroring at is when Koala asks FB again via an “…” method, to get the final token. It does a transfer of code for access_token, based on an exchange of credentials that are: the site-url, app-id, and app-secret.


  5. Comment by PrasannaKrishnamoorthy

    Posted on April 2, 2012 at 2:38 pm

    Ok. I'm ashamed to admit this, but I switched to Ruby 1.9.2 and this problem went away.

    Now a bit dissatisfied, since I wasn't able to nail the problem down, but don't have time to deal with it.

    Funnily enough 1.9.3 works fine in production, Linux. I am on Mac OS, and 1.9.3 doesn't work for me, and I need to use 1.9.2.

    Giving up for now.

    Thanks for the help!

  6. Comment by Allerin Tech Pvt Ltd

    Posted on May 3, 2012 at 8:44 am

    Sometimes it's very difficult to configure Facebook application. Thanks for sharing such useful data

  7. Comment by Jia Khalid

    Posted on June 19, 2012 at 12:58 pm

    i am trying to subscribe my application to facebook but the subscribtion call gives me following error
    (#2200) callback verification failed: Operation timed out after 6001 milliseconds with 0 bytes received
    any idea?

  8. Comment by standingwave

    Posted on July 27, 2012 at 12:47 am

    Hey, thanks for setting this up.  This is pretty much the only Koala example I've been able to find.  I cloned your app and dropped in my credentials and I'm getting an OAuth exception:

    “error”: {
    “message”: “Error validating application. Invalid application ID.”,
    “type”: “OAuthException”,
    “code”: 101
    }Any ideas what might be going on? Besides the obvious of checking and rechecking the FB App ID. :)

  9. Comment by banane

    Posted on July 27, 2012 at 5:06 pm

    Thanks for the praise!

    Sorry, yeah that is a pretty obvious error message, so there  probably is some typo in the app id somewhere- you can also echo/puts out the connect string (auth_url) and test in a browser to debug. 

  10. Comment by banane

    Posted on July 27, 2012 at 5:07 pm

    The callback path is probably wrong and/or the url you're using is different from the one you've registered in Facebook. Check the application settings.

  11. Comment by Dan Voell

    Posted on October 31, 2012 at 1:23 pm

    Thanks, this was simple and helpful!

  12. Comment by Mohit Arora So

    Posted on November 19, 2012 at 12:05 pm

    works like charm! thanks

  13. Comment by VII Identity

    Posted on January 5, 2013 at 11:23 pm

    Great article and thanks for hosting the sample app. I downloaded and just be forewarned that you'll need to do some updates if you are using an older version of Ruby 1.8.7 – which is the current version in the Ubuntu repos right now – see link here:… 

  14. Comment by banane

    Posted on January 20, 2013 at 9:40 pm

    Feel free to submit a PR

  15. Comment by Ram

    Posted on April 15, 2013 at 11:53 am

    This article is pretty good .

    Can you please provide me the detailed steps to provide fb signin for rails application using Koala gem.

    1. how to create access token
    2. canvas URL
    3. configuration
    So that it will helpful

    Thanks in Advance

  16. Comment by Harshvardhan Parihar

    Posted on July 1, 2014 at 1:32 pm

    I am using Koala to login using Facebook on my web app. After successfully login in, returning a correct value to session[:oauth] but it becomes string object after the callback.

    Before redirect session[:oauth] = #<koala::facebook::oauth:0xb3d9e118> and class of this object is Koala::Facebook::OAuth
    But after redirect from facebook login procedure this object becomes string
    session[:oauth] = '#<koala::facebook::oauth:0xb3d9e118>' and class = String

    Here is my code

    if params[:code].present?
    oauth_access_token = session[:oauth].get_access_token_info(params[:code])['access_token']
    @graph =
    friends = @graph.get_connections(“me”, “friends”)
    session[:oauth] =, app_secret, user_photos_url(current_user))

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>