我构建了一个应用程序,用户在其中登录并抛出 facebook 帐户,然后我会获取他们的朋友和他们的教育历史。它是这样的:
用户登录并转到 SessionsController#Create:
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env['omniauth.auth'])
end
end
SessionsController 方法 create 调用 User 模型中的 .from_omniauth 方法:
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
...more code...
user.save!
user.add_friends
end
end
.from_omniauth 方法调用了 User 模型中的 add_friends 方法:
def add_friends
friends_data = facebook.get_connections("me", "friends", :fields => "name, id, education")
friends_data.each do |hash|
friend.name = hash["name"]
friend.uid = hash["id"]
if hash["education"]
hash["education"].each do |e|
if e["type"] == "High School"
friend.highschool_name = e["school"]["name"] if (!hash["education"].blank? && !e["school"].blank?)
elsif e["type"] == "Graduate School"
friend.graduateschool_name = e["school"]["name"] if (!hash["education"].blank? && !e["school"].blank?)
end
end
end
friend.save!
friend
end
end
我收到此错误:
NameError in SessionsController#create
undefined local variable or method `friend' for #<User:0x007fad11d50eb0>
而且我知道这意味着我必须初始化变量朋友,但我不知道该怎么做。任何想法,这将非常有帮助!=)