2010-03-29 104 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应产生的集合的页面。