2010-03-29 133 views
4

我正在編寫一個應用程序,用戶既可以創建自己的頁面供用戶發佈,也可以關注用戶創建的頁面上的帖子。這裏是我的模型關係看起來像此刻...Rails的問題has_many關係

class User < ActiveRecord::Base 

has_many :pages 
has_many :posts 
has_many :followings 
has_many :pages, :through => :followings, :source => :user 

class Page < ActiveRecord::Base 

has_many :posts 
belongs_to :user 
has_many :followings 
has_many :users, :through => :followings 

class Following < ActiveRecord::Base 

belongs_to :user 
belongs_to :page 

class Post < ActiveRecord::Base 

belongs_to :page 
belongs_to :user 

麻煩發生在我試圖通過關係來工作,我的一路下滑,以創建頁面(以及相應的職位)的主頁給定(類似於您登錄時Twitter的用戶主頁的工作方式 - 一個頁面,爲您提供了來自您所關注頁面的所有最新帖子的綜合視圖)...

我收到了一個「找不到方法「錯誤,當我嘗試打電話followings.pages。理想情況下,我希望能夠以一種方式調用User.pages,使用戶可以關注他們的頁面,而不是他們創建的頁面。

我是一個編程和Rails的新手,所以任何幫助將不勝感激!我試圖儘可能多地搜索這個網站,然後發佈這個問題(還有許多谷歌搜索),但似乎沒有什麼特定於我的問題...

回答

4

您已經定義了兩次pages關聯。更改User類,如下所示:

class User < ActiveRecord::Base 
    has_many :pages 
    has_many :posts 
    has_many :followings 
    has_many :followed_pages, :class_name => "Page", 
       :through => :followings, :source => :user 
end 

現在讓我們來測試協會:

user.pages # returns the pages created by the user 
user.followed_pages # returns the pages followed by the user 
+0

另外,我可能會重命名'Page.user'到'Page.author',以便從'Page.users'消除歧義,或者把'Page.users'變成'Page.followers'。 – jamuraa 2010-03-29 15:09:10

+0

謝謝!這爲我解決了... – Tchock 2010-03-30 02:51:21

0

嘗試following.page而不是followings.pages?

+0

這似乎仍然給我一個未定義的方法錯誤(當我把它放在一個隨機的用戶)。 – Tchock 2010-03-29 04:07:24

0

至於你的理想,簡單的用戶模型應該足夠了(:源應推斷):

class User < ActiveRecord::Base 
    has_many :pages 
    has_many :posts 
    has_many :followings 
    has_many :followed_pages, :class_name => "Page", :through => :followings 
end class 

現在,使用許多-to-many關聯:以下,a_user.followed_pa​​ges應產生的集合的頁面。