2012-06-30 29 views
1

我正在使用rails 3應用程序並使用考拉寶石獲取到facebook圖表api.I的連接,我也使用omniauth來驗證用戶。SessionsController中的NoMethodError#在調用用戶模型中的方法時創建#

我得到以下錯誤:

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' 

在紅寶石的文檔,它說:「當一個方法被調用上沒有它定義,也沒有與響應的method_missing接收機提出了」

但我有一個metod定義,所以爲什麼我會得到這個錯誤?我該如何解決它?

在我SessionController我做這樣的事情:

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 

這是我的用戶模型:

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 

回答

1

在您發佈def add_friends實際上是你from_omniauth類方法等裏面的代碼最終也是類方法,而不是實例方法。

把那個(和facebook的方法)移出那裏,你應該沒問題。您可能也想調用您的facebook方法,而不是直接訪問實例變量。

+0

你可以請我看看,我移動的方法是這樣的:https://gist.github.com/3025599現在我得到一個get_connections insted:undefined方法'get_connections'爲零:NilClass – SHUMAcupcake

+0

您正在使用'@ facebook'沒有設置。做'facebook.get_connections(...)'而不是 –

+0

然後我得到:未定義的局部變量或方法'臉譜'爲#<用戶:0x007ff4a1760ff0> – SHUMAcupcake

相關問題