Hey,
I’ve somehow managed to get friendships working first try, but it’s not perfect.
First the code:
create_table :friendships do |t| t.column :initiator_id, :integer, :null => false
t.column :recipricator_id, :integer, :null => false
t.column :confirmed, :boolean, :null => false, :default => 0
end
class Friendship < ActiveRecord::Base belongs_to :recipricator,
:foreign_key => 'recipricator_id',
:class_name => 'User'
belongs_to :initiator,
:foreign_key => 'initiator_id',
:class_name => 'User'
end
class User < ActiveRecord::Base has_many :initiated_friendships, :foreign_key => ‘initiator_id’, :class_name => ‘Friendship’, :conditions => ‘confirmed = 1’
has_many :recipricated_friendships,
:foreign_key => 'recipricator_id',
:class_name => 'Friendship',
:conditions => 'confirmed = 1'
has_many :unconfirmed_friendship_requests,
:foreign_key => 'recipricator_id',
:class_name => 'Friendship'
has_many :unconfirmed_friendship_proposals,
:foreign_key => 'initiator_id',
:class_name => 'Friendship'
end
My first problem is that to get a User object from my friendship I’ve to do something like: current_user.unconfirmed_friendship_requests.first.initiator # Gets the User object of the user that made the friendship request
I’d like ‘unconfirmed_friendship_requests’ to contain all users that were associated with the initiator_id, I don’t care about the recipricator_id as that’s always the current user. The same goes for ‘unconfirmed_friendship_proposals’ but the opposite.
The second problem, is that to get all the friends of a user I need to iterate over initiated_friendships and recipricated_friendships. I’d like to just do current_user.friends.
btw, I don’t like those friendship systems where you can befriend a user despite them not wanting you to, hence why I’ve used a confirmed flag.
Cheers, Ian.