2016-07-23 33 views
0

我很困擾Ruby on Rails關係,我非常感謝你的幫助。如何在Rails中創建follower和followee?

有無模型用戶

class User < ActiveRecord::Base 
    has_many :followers, :through => :follows, foreign_key: "followee_id" 
    has_many :followees, :through => :follows, foreign_key: "follower_id" 
end 

和模型按照

class Follow < ActiveRecord::Base 
    belongs_to :followee, class_name: "User" 
    belongs_to :follower, class_name: "User" 
end 

,但如果要創建新的跟隨者,如:

user.followers << User.first 

結果是SystemStackError

謝謝你的幫助!

+1

代替'foreign_key的:「followee_id」'你應該使用'來源:followee' –

回答

1

你必須嘗試這樣的事:

class User < ActiveRecord::Base 
     has_many :follower_follows, foreign_key: :followee_id, class_name: "Follow" 
     has_many :followers, through: :follower_follows, source: :follower 
     has_many :followee_follows, foreign_key: :follower_id, class_name: "Follow" 
     has_many :followees, through: :followee_follows, source: :followee 
    end 

這裏follower_follows和followee_follows的連接表和源:在後續模型和源極跟隨器識別:跟隨與belong_to匹配:關注者與匹配belong_to:關注者識別在後續模型

我認爲這將工作你的情況