2012-12-13 112 views
1

我實現了「跟隨」功能。顯示「用戶A以下的人」很簡單,但是顯示「關注用戶A的人」給我帶來麻煩。Rails 3 ActiveRecord查詢問題

我有follow_links,其中有id,user_id和follow_you_id列。當用戶A開始關注用戶B時,這些列將會像(user_id = A,follow_you_id = B)。

爲了表明A(@user)跟隨用戶,我可以簡單地做

@follow_yous = @user.follow_yous 

但我不知道如何顯示誰是下一個(@user)用戶

要做到這一點,我首先找到了所有相關的鏈接。

@follow_links = FollowLink.where(:follow_you_id => @user.id) 

現在,我想我可能只是做@follow_mes = @follow_links.users,但它說user是一個未定義的方法。所以我想我可以撥打user.follow_yousfollow_you.users

我的下一個方法是

@follow_links = FollowLink.where(:follow_you_id => @user.id) 
@follow_mes = User.where(:id => @user.id, :include => @follow_links) 

我打算找曾提供@follow_links對象的所有用戶對象,但我認爲語法錯了。經過一番研究,我找不到一個像樣的解決方案。我會很感激任何幫助。

更新: FollowLink模式

belongs_to :user 
    belongs_to :follow_you, :class_name => "User" 
+0

什麼是你'FollowLink'模型看起來像?你必須在那裏建立兩種不同類型的用戶(追隨者和追隨者)的關係。 – Mischa

+0

@Mischa,請檢查我的更新。 –

+0

查看我的回答。請讓我知道這是否適合你。 – Mischa

回答

2

您可以使用joins這樣的:

@users = User.joins(:follow_links).where(:follow_links => { :follow_you_id => @user.id }) 
+0

謝謝。這工作得很好。你能爲我解釋一下嗎?這意味着user.follow_links會調用正確的對象。那麼follow_link.users怎麼不叫用戶呢? –

+1

@MaximusS,因爲'User has_many:follow_links',但'FollowLink belongs_to:user'。這意味着你只能執行'follow_link.user',而不能'follow_link.users'。你必須編寫一個像上面這樣的特定查詢來獲取你想要的信息。 ActiveRecord不支持它。 – Mischa

+0

你的意思是'user.follow_links'只允許,對不對?我不再困惑。謝謝您的回答。 –

1

您可以使用下列內容:

@follow_links = FollowLink.where(:follow_you_id => @user.id) 
@follow_links.collect(&:user) # :user should be the name of your relation to user in your followlink model 
=> [User1, User2,...] 
+1

這是可能的,但它可能會產生大量的查詢。 – Mischa