2011-08-30 19 views
0

我是Rails的新手,完成了Michael Hartl的「Ruby on Rails 3教程」。雖然這本書教我很多,但我發現這個難題我不明白。Ruby on Rails:has_many引用 - 它擁有哪個模型對象?

要預覽的困擾,那就是,我不明白,用戶模型中,

has_many :following, :through=>:relationship, :source=>:followed 

如何這段代碼鏈接「user.following」以用戶實例的數組。

下面是整個難題。

首先,我有關係模型,記錄followed_idfollower_id的相關信息。裏面關係模型,該協會是簡單

class Relationship < ActiveRecord::Base 
    attr_accessible :followed_id 

    belongs_to :follower, :class_name => "User" 
    belongs_to :followed, :class_name => "User" 
end 

然後,用戶模型中,用戶將承擔跟隨的作用,並通過關係收集的關係表中所有的以下協會。

class User < ActiveRecord::Base 
    . 
    . 
    . 
    has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy 
    . 

直到現在,我明白了。

但在下一行發生混淆,通過user.following它可以組裝所有該用戶的以下(用戶實例)。像這樣,

has_many :following, :through=>:relationships, :source=>:followed 

我明白:源=>:跟着將覆蓋默認,並讓找到與該用戶相關聯的所有followed_ids

,Rails這樣可以識別followed_id鏈接到用戶對象?標籤名稱不匹配用戶,也不存在:class_name指定。我只是不明白Rails如何完成這項基礎工作,或者我錯過了一些提示。

謝謝! :)

回答

1

但是,Rails如何識別followed_id以鏈接到User對象? 標籤名稱與用戶不匹配,也不存在:指定的class_name。我不知道Rails如何完成這項基礎工作,或者我錯過了一些 提示。

Rails認識到這是一個用戶對象,因爲它在關係的belongs_to中設置。 Rails在這裏執行的操作是通過外鍵「follower_id」關注關係類,並返回與當前用戶具有關係的每個用戶,如下所示。當然,Rails的做,在這樣一個SQL語句:

SELECT `users`.* FROM `users` INNER JOIN `relationships` ON `relationships`.followed_id = `users`.id WHERE ((`relationships`.follower_id = <the current user id> )) 
+0

我可以解釋的是,通過'belongs_to'關係模型的關聯,是成功的,因爲用戶有':源=>:followed'和關係還定義'belongs_to:跟隨'? –

+0

準確地說,Rails知道它是一個用戶,因此。 – cicloon

+0

我明白了,謝謝不是! –

0
has_many :following, :through=>:relationships, :source=>:followed 

這說明到Rails的是followingfollowing的反比關係,並且用戶有很多的追隨者,並隨後通過他的關係。

Rails知道followed_id鏈接到用戶的方式是它在您的Relationship模型中定義。

希望你明白了!祝你好運:)