我正在开发 Rails 3 应用程序并使用 koala gem 连接到 facebook graph api。我还使用omniauth 来验证用户。
我收到以下错误:
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'
在 ruby 文档中它说:“在没有定义它的接收器上调用方法并且也无法使用 method_missing 响应时引发。”
但是我定义了一个方法,那么为什么会出现此错误?我该如何解决?
在我的 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