I am working on rails 3 and using the koala gem to get a connection to the facebook graph api. And I am using omniauth to autenticate users.
So when a new user logs to the site, the session_controller handles the new user:
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
The create method call the "from_omniauth" class metod in the User.rb model, to create a new user:
class User < ActiveRecord::Base
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"]
end
user.save!
end
I would like to save user facebook friends also and store it in a separate tabel called friends, so I made this friend model:
class Friend < ActiveRecord::Base
attr_accessible :name
belongs_to :user
validates :user_id, presence: true
def facebook
@Facebook ||= Koala::Facebook::API.new(token)
end
def add_friends
facebook { |fb| fb.get_connection("me", "friends") }
end
end
But I am lost on how to store users friends, I whould like to know:
> [{"name"=>"Johan Gyllenspetz", "id"=>"3624556"}, {"name"=>"Gustaf Josefsson",
. And I would like to store the name and uid. This is how I'd do this:
class User < ActiveRecord::Base
has_many :friends
def self.from_omniauth(auth)
user = 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"]
end
user.add_friends
user.save
user
end
def add_friends
@facebook.get_connection("me", "friends").each do |hash|
self.friends.where(:name => hash['name'], :uid => hash['id']).first_or_create
end
end
private
def facebook
@facebook ||= Koala::Facebook::API.new(token)
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.