2010-05-04 25 views
1

基本上,我的rails應用程序中有一個用戶模型和一個fanship模型,以方便用戶成爲彼此的「粉絲」。在rails中訪問用戶和用戶關係的雙方

在我的用戶模型中,我有:

has_many :fanships 
has_many :fanofs, :through => :fanships 

在我fanship模型中,我有:

belongs_to :user 
belongs_to :fanof, :class_name => "User", :foreign_key => "fanof_id" 

我fanship表主要包括:ID,:USER_ID和:fanof_id。這一切工作正常,我可以看到一個特定的用戶是用戶的像扇子:

<% @user.fanofs.each do |fan| %> 
    #things 
<% end %> 

我的問題是,怎樣才能得到屬於此特定用戶的粉絲用戶的列表?

我喜歡它,如果我可以只是有像@ user.fans的東西,但如果這是不可能的什麼是最有效的方式去做這個?

謝謝!

+0

http://iterat.ive.ly/index.php/2010/08/31/a-user-friend-relationship -model-in-rails/ – devanand 2012-03-07 14:09:29

回答

2

添加在用戶模型:

has_many :my_fanclubs, :class_name => 'Fanship', :foreign_key => 'fanof_id' 
has_many :fans, :through => :my_fanclubs, :source => :user, :class_name => 'User' 

(未測試)

+0

在第二行中,我將source =>'user_id'更改爲:source =>:user,並且它工作正常!謝謝 – Lowgain 2010-05-04 16:44:42

+0

謝謝,我糾正了它。 – klew 2010-05-04 16:48:02