我是Rails的新手,完成了Michael Hartl的「Ruby on Rails 3教程」。雖然這本書教我很多,但我發現這個難題我不明白。Ruby on Rails:has_many引用 - 它擁有哪個模型對象?
要預覽的困擾,那就是,我不明白,用戶模型中,
has_many :following, :through=>:relationship, :source=>:followed
如何這段代碼鏈接「user.following」以用戶實例的數組。
下面是整個難題。
首先,我有關係模型,記錄followed_id和follower_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如何完成這項基礎工作,或者我錯過了一些提示。
謝謝! :)
我可以解釋的是,通過'belongs_to'關係模型的關聯,是成功的,因爲用戶有':源=>:followed'和關係還定義'belongs_to:跟隨'? –
準確地說,Rails知道它是一個用戶,因此。 – cicloon
我明白了,謝謝不是! –