Rails has_many关系麻烦 [英] Trouble with Rails has_many relationships

查看:95
本文介绍了Rails has_many关系麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,用户可以在其中创建自己的页面供人们发布,也可以关注用户创建的页面上的帖子.这是我目前的模型关系...

I'm writing an app where a user can both create their own pages for people to post on, and follow posts on pages that users have created. Here is what my model relationships look like at the moment...

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的用户首页的工作方式-页面)可以为您提供所关注页面中所有最新帖子的合并视图)...

The trouble happens when I try to work my way down through the relationships in order to create a homepage of pages (and corresponding posts) a given user is following (similar to the way Twitter's user homepage works when you login - a page that provides you a consolidated view of all the latest posts from the pages you are following)...

当我尝试调用followings.pages时,出现未找到方法"错误.理想情况下,我希望能够通过某种方式调用User.pages,使我可以看到用户正在关注的页面,而不是他们创建的页面.

I get a "method not found" error when I try to call followings.pages. Ideally, I'd like to be able to call User.pages in a way that gets me the pages a user is following, rather than the pages they have created.

我是一名编程人员,也是Rails的新手,因此,非常感谢您的帮助!在发布此问题(以及众多Google搜索)之前,我尝试过尽可能多地搜索该网站,但是似乎没有什么问题比我的问题更具体...

I'm a programming and Rails newb, so any help would be much appreciated! I tried to search through as much of this site as possible before posting this question (along with numerous Google searches), but nothing seemed as specific as my problem...

推荐答案

您已经两次定义了pages关联.更改您的User类,如下所示:

You have defined the pages association twice. Change your User class as follows:

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

这篇关于Rails has_many关系麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆