Created
December 3, 2011 23:56
-
-
Save omarqureshi/1428553 to your computer and use it in GitHub Desktop.
friendships_schema.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Friendship < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :friend, :class_name => "User" | |
validates_presence_of :friend_id | |
validates_presence_of :user_id | |
validates_inclusion_of :accepted, :in => [true, false] | |
validates_uniqueness_of :friend_id, :scope => [:user_id] | |
validate :unique_friendship_record, :cannot_be_own_friend | |
attr_accessible :user_id, :friend_id | |
def unique_friendship_record | |
errors.add(:base, "Friendship record must be unique") if Friendship.for(friend_id, user_id).first | |
end | |
def cannot_be_own_friend | |
errors.add(:base, "Cannot be your own friend") if friend_id == user_id | |
end | |
scope :for, lambda {|a,b| | |
where("(friend_id = :one and user_id = :two) | |
or (user_id = :one and friend_id = :two)", | |
:one => a, :two => b)} | |
scope :accepted, where("accepted") | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create | |
@friendship = Friendship.where(:friend_id => current_user.id, :user_id => params[:user_id]).first | |
if @friendship | |
@friendship.accepted = true | |
else | |
@friendship = current_user.friendships.build(:friend_id => params[:user_id]) | |
end | |
if @friendship.save | |
flash[:success] = "Added friend." | |
redirect_to params[:return_to] || root_url | |
else | |
flash[:error] = "Unable to add friend." | |
redirect_to params[:return_to] || root_url | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Table "public.friendships" | |
Column | Type | Modifiers | |
------------+-----------------------------+---------------------------------------------------------- | |
id | integer | not null default nextval('friendships_id_seq'::regclass) | |
user_id | integer | not null | |
friend_id | integer | not null | |
created_at | timestamp without time zone | | |
updated_at | timestamp without time zone | | |
accepted | boolean | not null default false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment