在rails中初始化的朋友模型

时间:2012-07-10 14:38:33

标签: ruby-on-rails ruby ruby-on-rails-3

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

我知道这意味着我必须初始化变量朋友,但我不知道如何做到这一点。任何想法,都会非常有帮助! =)

2 个答案:

答案 0 :(得分:2)

在循环中使用friend = Friend.new

friends_data.each do |hash|
    friend = Friend.new   # <-----------
    friend.name = hash["name"]
    friend.uid = hash["id"]

答案 1 :(得分:0)

首先你需要朋友模特:

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