0

我构建了一个应用程序,用户在其中登录并抛出 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>

而且我知道这意味着我必须初始化变量朋友,但我不知道该怎么做。任何想法,这将非常有帮助!=)

4

2 回答 2

2

friend = Friend.new在循环中使用:

friends_data.each do |hash|
    friend = Friend.new   # <-----------
    friend.name = hash["name"]
    friend.uid = hash["id"]
于 2012-07-10T14:41:54.393 回答
0

首先你需要 Friend 模型:

rails g model Friend user_id:integer uid:string name:string highschool_name:string graduateschool_name:string
rake db:migrate

在朋友类中放入belongs_to:

class Friend < ActiveRecord::Base
   belongs_to :user
end

在用户类中放入 has_many:

class User < ActiveRecord::Base
   has_many :friends
end

现在您的add_friend 方法应该如下所示:

def add_friends
    friends_data =  facebook.get_connections("me", "friends",   :fields => "name, id, education")
    friends_data.map do |hash|
      friend=Friend.new
      friend.name = hash["name"]
      friend.uid = hash["id"]
      friend.user_id = self.id

      if hash["education"]
        hash["education"].each do |e|
          next if e["school"].blank?
          if e["type"] == "High School"
            friend.highschool_name = e["school"]["name"]
          elsif e["type"] == "Graduate School"
            friend.graduateschool_name = e["school"]["name"]
          end
        end
      end
      friend.save!
      friend
    end
  end
于 2012-07-10T14:50:49.663 回答