Search code examples
ruby-on-railsrubyruby-on-rails-3facebook-fqlkoala

undefined method `fql_query' for nil:NilClass


With the koala gem I am trying to count checkins for a page. I am using rails.

In my user.rb I have a method for getting a new connection to the Facebook graph:

class User < ActiveRecord::Base
 def facebook
     @facebook ||= Koala::Facebook::API.new(oauth_token)
 end
end

In my school.rb I have a method for counting the checkins:

class school < ActiveRecord::Base
 def count_checkins(name)
  checkins = @facebook.fql_query("SELECT checkins FROM page WHERE name = #{name}")
 end
end

And I am calling it from the view like this:

<%= @school.count_checkins(@school.name) %>

But I get the following error:

undefined method `fql_query' for nil:NilClass

Dont really understand why I get this error, any help would be wonderful.


Solution

  • It looks like you haven't actually created the @facebook object inside your School model. We'd need to see the rest of your school.rb file to know for sure. I'd suggest you create the object inside your School.initialize() method like so:

    def initialize(oauth_token)
      unless oauth_token.nil?
        @facebook = Koala::facebook::API.new(oauth_token)
      end
    end
    

    In order for this to work, you'll need to pass the desired oauth_token to your School.new() call. Then you'll have one @facebook object for each School.

    Edit

    After looking at the gist, I realized that you had actually intantiated a User object, and called the facebook method on that. That is actually the better way to do it. The problem is, you're using @current_user, which would have to be setup as a property of the school model. You probably meant to use the helper function current_user instead.

     def count_checkins(name)
      u = current_user
      [email protected]_query("SELECT checkins FROM page WHERE name = #{name}")
     end
    

    Try that and see what happens. At the very least, you should get a different error message.

    Edit 2

    So, now I'm thinking the current_user function should be called in controller code, not model code. This is because the current user is something that doesn't really exist except as part of an active request. Therefore, we should take User u as a parameter to the count_checkins function like so:

    def count_checkins(name, u)
      u.facebook.fql_query("SELECT checkins FROM page WHERE name = #{name}")
    end
    

    You'll need to change the code where you call count_checkins() too:

    count_checkins(name, current_user)
    

    That should do it. Let's see!