自引用关联用于将模型与其自身关联。最常见的例子是管理朋友和他的跟随者之间的关联。
例如
rails g model friendship user_id:references friend_id:integer
现在您可以将模型关联起来;
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
另一个模型看起来像;
class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => "User" end