Self-Referential Association

suggest change

A self-referential association associates a model with itself. A frequent example is a user and that user's friends.

For example:

rails generate model friendship user:references friend:references

belongs_to :friend needs a real friend_id reference. friend_id:integer creates the column, but not as a reference.

Now you can associate the models like this:

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

The other model looks like this:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents