Ruby on Rails ActiveRecord Associations Self-Referential Association


Example

Self-referential association is used to associate a model with itself. The most frequent example would be, to manage association between a friend and his follower.

ex.

rails g model friendship user_id:references friend_id:integer

now you can associate models like;

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end

and the other model will look like;

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
end