I need to create a user Friendship (user1_id, user2_id)
model which connects users.
I would like to avoid having to create two Friendship
records for every user / friend as a friendship goes both ways.
How would you do this so while having a somewhat simple
# User.rb
has_many :friendships
has_many :friends, :through => :friendships, :class_name => "User"
EDIT My solution was to mirror the records:
class Friendship < ActiveRecord::Base
belongs_to :user1
belongs_to :user2
after_create :create_mirror!
after_destroy :destroy_mirror!
validate :does_not_exist
def mirror_record
Friendship.where(:user1_id => user2.id, :user2_id => user1.id).first
end
private
def does_not_exist
errors.add(:base, 'already exists') if Friendship.where(:user1_id => user1.id, :user2_id => user2.id) rescue nil
end
def create_mirror!
Friendship.create(:user1 => user2, :user2 => user1)
end
def destroy_mirror!
mirror_record.destroy if mirror_record
end
end