Rails, self-referential association on the User model to define friends/followers
I’m trying to create a friendship association. I found and have been following the the tutorial:
- Rails 3 gem for capturing referrer info?
- Ruby on Rails: Mass-Assignment on iteration in loop?
- Ruby on Rails paperclip questions
- Resque multiple workers in development mode
- Missing Method MySQL2
- Omniauth not working
The problem with the tutorial is there is not concept of status (Accept,Pending,Ignored)
Any ideas on how to create this type of relationship but have a status, so when you friend request it is pending until the correct user either accepts or ignores?
One Solution collect form web for “Rails, self-referential association on the User model to define friends/followers”
Assuming that the both participants in the friendship might also have other friendships, then you need somewhere to store state of this particular friendship. That is an indication that you need a join model which you can get through a has_and_belongs_to_many. Then your status can be stored in the join table (Friendship in this case)
class Person< ActiveRecord::Base has_many :friendships has_many :friends, :class_name => "Person", :through => :friendships end class Friendship < ActiveRecord::Base belongs_to :friend1, :class_name => "Person" belongs_to :friend2, :class_name => "Person" end
But as you might notice from the kludgy friend1 and friend2, the issue you are about to hit is that you probably want Friendship as a non directed relationship.
That’s a too big a topic to detail here, but here’s one place it’s addressed:
a promising looking article that I haven’t actually used
Then finally note that while a friendship is bi-direction, a friendship request is not–in the case of a request you need to know who issued it and who received it. So I’d guess you’ll want a bi-directional friendship relationship and a friend_request relationship which is directed. When the request is approved that relationship is removed and you add the bi-directional friendship.