Self-Referential Association

Self-referential association use to associate model it self. Its use to manage friend and follower relationship.

ex.

rails g model friendship user_id:references friend_id:integer

now you can associate model 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 your another model look like

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

results matching ""

    No results matching ""