user592638
user592638

Reputation:

NoMethodError in SessionsController#create when calling a method in user model

I am working on rails 3 app and using the koala gem to get a connection to the facebook graph api.I am also using omniauth to autenticate users.

I get the following error:

NoMethodError in SessionsController#create
undefined method `add_friends' for #<User:0x007fcfcb1a87e8>

app/models/user.rb:28:in `block in from_omniauth'
app/models/user.rb:6:in `tap'
app/models/user.rb:6:in `from_omniauth'
app/controllers/sessions_controller.rb:3:in `create'

In ruby docs it says: "Raised when a method is called on a receiver which doesn't have it defined and also fails to respond with method_missing."

But I have a metod defined, so why do I get this error? And how can I fix it?

In my SessionController I do something like this:

class SessionsController < ApplicationController
  def create
    user = User.from_omniauth(env['omniauth.auth'])
    session[:user_id] = user.id
    redirect_to root_url, notice: "Signed in!"
  end
end

This is my user model:

class User < ActiveRecord::Base
  #attr_accessible :provider, :uid, :token, :email, :name, :first_name, :last_name, :image, :gender, :location, :school, :year
  has_many :friends

  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.first_name = auth["info"]["first_name"]
      user.last_name = auth["info"]["last_name"]
      user.image = auth["info"]["image"]
      user.email = auth["info"]["email"]
      user.gender = auth["extra"]["raw_info"]["gender"]
      user.location = auth["extra"]["raw_info"]["location"]["name"]          
      user.token = auth["credentials"]["token"]

      user.add_friends
      user.save!
      user

    end

    def add_friends
      @facebook.get_connections("me", "friends").each do |hash|
        self.friends.find(:name => hash['name'], :uid => hash['id']).first_or_create
      end
    end

    private 

    def facebook
      @facebook ||= Koala::Facebook::API.new(token)
    end
  end
end

Upvotes: 1

Views: 1390

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84182

In the code you posted def add_friends is actually inside your from_omniauth class method and so ends up being a class method too, rather than an instance method.

Move that (and the facebook method) out of there and you should be ok. You probably also want to be calling your facebook method rather than accessing the instance variable directly.

Upvotes: 1

Related Questions