Skip to content

Instantly share code, notes, and snippets.

@FranciscoPinto
Created May 27, 2012 04:47
Show Gist options
  • Save FranciscoPinto/2802211 to your computer and use it in GitHub Desktop.
Save FranciscoPinto/2802211 to your computer and use it in GitHub Desktop.
class FriendshipsController < ApplicationController
def index
@friends = User.find(params[:user_id]).friends
respond_to do |format|
format.json { render json: @friends }
end
end
def create
@user = User.find(params[:user_id])
@friend = User.find(params[:id])
@friendship = Friendship.new(:user => @user, :friend => @friend)
if @friendship.save
respond_to do |format|
format.json { render json: @friendship, status: :created }
end
else
respond_to do |format|
format.json { render json: @friendship.errors, status: :unprocessable_entity }
end
end
end
def destroy
@user = User.find(params[:user_id])
@friend = User.find(params[:id])
@friendship = Friendship.find_by(:user => @user, :friend => @friend)
@friendship.destroy
respond_to do |format|
if @user.save
format.json { render json: @user, status: :created }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => User, :foreign_key => :friend_id
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :token_authenticatable
has_many :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :direct_friends, :through => :friendships, :source => :friend
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
has_many :book_users
has_many :books, :through => :book_users, :uniq => true
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :books
def friends
direct_friends | inverse_friends
end
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = self.find_by_email(data.email)
user
else # Create a user with a stub password.
self.create(:email => data.email, :password => Devise.friendly_token[0,20])
end
end
def self.find_for_google_oauth(access_token, signed_in_resource=nil)
data = access_token.info
if user = User.where(:email => data["email"]).first
user
else
User.create!(:email => data["email"], :password => Devise.friendly_token[0,20])
end
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
user.email = data["email"]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment