RailsCasts Pro episodes are now free!
Learn more or hide this
GitHub User: weiserma
I came up with this solution to bidirectional with methods for: * mutual - relationship in both directions * pending - relationship only forward * requesting - relationship only backward
class Friend < ActiveRecord::Base belongs_to :profile belongs_to :friend, :class_name => 'Profile' end
class Profile < ActiveRecord::Base has_many :friends has_many :friend_profiles, :through => :friends, source: :friend has_many :friended_by, class_name: "Friend" , :foreign_key => "friend_id" has_many :friended_by_profiles, :through => :friended_by, source: :profile def mutual_friends friended_by.where('profile_id in (?)', friend_profile_ids) end def mutual_friend_profiles Profile.where('id in (?)', mutual_friends.pluck(:profile_id)) end def requesting_friends friended_by.where('profile_id not in (?)', friend_profile_ids) end def requesting_friend_profiles Profile.where('id in (?)', requesting_friends.pluck(:profile_id)) end def pending_friends friends.where('friend_id not in (?)', friended_by_profile_ids) end def pending_friend_profiles Profile.where('id in (?)', pending_friends.pluck(:friend_id)) end end
Any suggestions for improvement?
I came up with this solution to bidirectional with methods for:
* mutual - relationship in both directions
* pending - relationship only forward
* requesting - relationship only backward
Any suggestions for improvement?