2010-08-03 78 views
12

我試圖代表我的應用程序中的用戶之間的關係,其中用戶可以有許多追隨者,並可以跟隨其他用戶。 我想有一些像user.followers()和user.followed_by() 請你詳細告訴我如何使用ActiveRecord來表示這個?關係類似Twitter的追隨者/關注ActiveRecord

謝謝。

回答

30

您需要兩個模型,一個Person和追隨中

rails generate model Person name:string 
rails generate model Followings person_id:integer follower_id:integer blocked:boolean 

以及模型中的以下代碼

class Person < ActiveRecord::Base 
    has_many :followers, :class_name => 'Followings', :foreign_key => 'person_id' 
    has_many :following, :class_name => 'Followings', :foreign_key => 'follower_id' 
end 

,並在追隨中類對應你寫

class Followings < ActiveRecord::Base 
    belongs_to :person 
    belongs_to :follower, :class_name => 'Person' 
end 

你可以做的更清晰的名稱根據自己的喜好(我特別不喜歡Followings -name),但這應該讓你開始。

2

Twitter的追隨者模型與友情模型的不同之處在於,您不需要該人員的許可就可以關注他們。在這裏,我設置了一個延遲加載,在person對象中沒有完全定義關係。

/app/models/person.rb

def followers 
    Followership.where(:leader_id=>self.id).not_blocked 
    end 

    def following 
    Followership.where(:follower_id=>:self.id).not_blocked 
    end 
    has_many :followers, :class_name=>'Followership' 
    has_many :followed_by, :class_name=>'Followership' 

/app/models/followership.rb

belongs_to :leader, :class_name=>'Person' 
    belongs_to :follower, :class_name=>'Person' 

    #leader_id integer 
    #follower_id integer 
    #blocked boolean 

    scope :not_blocked, :conditions => ['blocked = ?', false]