Reputation:
I building an app where a user sign in throw there facebook account and the I grab their friends and their education history. It goes something like this:
The user signs in and goes to the SessionsController#Create:
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env['omniauth.auth'])
end
end
The SessionsController method create calls the method .from_omniauth in the User model:
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
The .from_omniauth method calls the method add_friends which is inside the User model:
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
I get this error:
NameError in SessionsController#create
undefined local variable or method `friend' for #<User:0x007fad11d50eb0>
And I know this means that I have to initialized variable friend, but I have no idea about how to do that. Any ideas, it would be very helpful! =)
Upvotes: 0
Views: 142
Reputation: 5933
First you need Friend model:
rails g model Friend user_id:integer uid:string name:string highschool_name:string graduateschool_name:string
rake db:migrate
In friend class put belongs_to:
class Friend < ActiveRecord::Base
belongs_to :user
end
In user class put has_many:
class User < ActiveRecord::Base
has_many :friends
end
Now your add_friend
method should looks like this:
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
Upvotes: 0
Reputation: 13925
Use friend = Friend.new
in the loop:
friends_data.each do |hash|
friend = Friend.new # <-----------
friend.name = hash["name"]
friend.uid = hash["id"]
Upvotes: 2