我正在编写一个应用程序,用户既可以创建自己的页面供人们发帖,也可以关注用户创建的页面上的帖子。这是我目前的模型关系的样子......
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 新手,所以任何帮助将不胜感激!在发布这个问题之前,我尝试尽可能多地搜索该网站(以及大量的谷歌搜索),但似乎没有什么比我的问题更具体的了......
您已经定义了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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)